我是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文档字段,然后在搜索中使用它的方法。这样做的惯用方法是什么?
如果有任何帮助,我将不胜感激。
非关系数据库的好处是,可以稍微冗余一点,并且由于您没有将所有东西连接在一起,因此检索起来更快。您可以按照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将文档存储在集合中。集合类似于关系数据库中的表。
如果您对关系数据库不熟悉,则表实际上将代表一种类型的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句