我正在尝试使用Go向MongoDB插入一些数据。
这里是数据结构:
type Entry struct {
Id string `json:"id",bson:"_id,omitempty"`
ResourceId int `json:"resource_id,bson:"resource_id"`
Word string `json:"word",bson:"word"`
Meaning string `json:"meaning",bson:"meaning"`
Example string `json:"example",bson:"example"`
}
这是我的插入函数:
func insertEntry(db *mgo.Session, entry *Entry) error {
c := db.DB(*mongoDB).C("entries")
count, err := c.Find(bson.M{"resourceid": entry.ResourceId}).Limit(1).Count()
if err != nil {
return err
}
if count > 0 {
return fmt.Errorf("resource %s already exists", entry.ResourceId)
}
return c.Insert(entry)
}
最后,这就是我称之为的方式:
entry := &Entry{
ResourceId: resourceId,
Word: word,
Meaning: meaning,
Example: example,
}
err = insertEntry(db, entry)
if err != nil {
log.Println("Could not save the entry to MongoDB:", err)
}
问题是,我本来期望我的bson
标签可以神奇地工作,但它们没有。数据保存时应该是这个样子的:
{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "resource_id" : 7660708, "word" : "Foo" ...}
但实际上保存成了这个样子:
{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "id" : "", "resourceid" : 7660708, "word" : "Foo"...}
我该如何解决这个问题?