如何使用mgo在单个集合中使用多种类型

时间:2017-05-23 12:28:26

标签: mongodb go mgo

我是golang的新手,并尝试使用mongodb作为支持数据库编写一个简单的事件源用户管理webapi。现在我有User,看起来像这样:

type User struct {
Id       bson.ObjectId `json:"id" bson:"_id"`
UserName string        `json:"username" bson:"username"`
Email    string        `json:"email" bson:"email"`
PwdHash  string        `json:"pwd_hash" bson:"pwd_hash"`
FullName string        `json:"fullname" bson:"fullname"`
}

当有人使用api时,发生在用户身上的三个事件:

type UserCreatedEvent struct {
    UserId         bson.ObjectId `json:"id" bson:"_id"`
    //time when event was issued
    CreatedEpoch   time.Time     `json:"created_epoch" bson:"created_epoch"`
    //id of user that made a change
    IssuedByUserId bson.ObjectId `json:"issuedby_userid" bson:"issuedby_userid"`
}

type UserDeletedEvent struct {
    UserId         bson.ObjectId `json:"id" bson:"_id"`
    CreatedEpoch   time.Time     `json:"created_epoch" bson:"created_epoch"`
    //id of user that made a change
    IssuedByUserId bson.ObjectId `json:"issuedby_userid" bson:"issuedby_userid"`
}

type UserUpdatedEvent struct {
    UserId         bson.ObjectId `json:"id" bson:"_id"`
    CreatedEpoch   time.Time     `json:"created_epoch" bson:"created_epoch"`
    //id of user that made a change
    IssuedByUserId bson.ObjectId `json:"issuedby_userid" bson:"issuedby_userid"`
    ChangedFieldName     string  `json:"changed_field_name" bson:"changed_field_name"`
    NewChangedFieldValue string  `json:"new_changed_field_value" bson:"new_changed_field_value"`
}

现在我一直坚持从db保存和检索事件。问题是我想将它们存储在一个集合中,以便我有一个完整的用户修改历史记录。但我找不到如何正确存储事件类型名称作为mongo文档字段,然后在搜索中使用它。这样做的惯用途是什么?

我会感激任何帮助。

1 个答案:

答案 0 :(得分:0)

非关系型数据库的优点是,一点点冗余是可以的,并且检索速度更快,因为您不会将事物连接在一起。您可以在User上以对您和您的数据有意义的方式添加底部三个对象作为属性。那么您也不需要将UserId存储在这些对象上。

如果您需要快速搜索Events,则可以创建另一个集合来保存它们。您要插入两个集合,但检索时间/逻辑应该非常好/易于编写。

您的新Event类似于:

type UserEventType int

const (
    Created UserEventType = iota
    Deleted
    Updated
)

type UserEvent struct {
    UserId               bson.ObjectId `json:"id" bson:"_id"`
    CreatedEpoch         time.Time     `json:"created_epoch" bson:"created_epoch"`
    //id of user that made a change
    IssuedByUserId       bson.ObjectId `json:"issuedby_userid" bson:"issuedby_userid"`
    ChangedFieldName     string        `json:"changed_field_name,omitempty" bson:"changed_field_name,omitempty"`
    NewChangedFieldValue string     `json:"new_changed_field_value,omitempty" bson:"new_changed_field_value,omitempty"`
    EventType            UserEventType `json:"user_event_type" bson:"user_event_type"`
}

请注意omitempty在可选字段上,具体取决于事件类型。

你真的不应该在同一个集合中存储不同的对象。以下是Mongo文档中的一行:

  

MongoDB将文档存储在集合中。集合类似于关系数据库中的表。

如果您不熟悉关系数据库,表格基本上代表一种类型的对象。

相关问题