【发布时间】:2014-06-29 05:41:46
【问题描述】:
我正在尝试使用 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, “单词” : “Foo” ...}
它被保存为:
{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "id" : "", “resourceid”:7660708,“word”:“Foo”...}
我该如何解决这个问题?
【问题讨论】: