英文:
Upsert issue when using mgo
问题
请告诉我在使用mgo操作Mongo时遇到这个问题的人是谁。我需要更新文档,如果文档不存在,则插入一个新文档,我使用Upsert()方法:
entry := models.Example{
ID: bson.NewObjectId(),
UserID: userID,
SessionID: sessionID,
Created: created,
}
query := bson.M{
"$set": entry,
}
_, err = mongo.C(mongodb.ExampleCollection).Upsert(bson.M{
"user_id": userID,
"session_id": sessionID,
}, query)
所以它可以插入文档,但在更新时会出错(&mgo.LastError {Err: "Performing an update on the path '_id' would modify the immutable field '_id'", ...}),如果删除之前生成的ID,则无法在没有ID的情况下插入它。
我还了解到了$setOnInsert,但显然它在ID上不起作用:
query := bson.M{
"$setOnInsert": bson.M{
"_id": bson.NewObjectId(),
},
"$set": entry,
}
英文:
Please tell me who came across this when working with Mongo through mgo. I need to update the document, if there is no document, insert a new one, I use Upsert():
entry := models.Example{
ID: bson.NewObjectId(),
UserID: userID,
SessionID: sessionID,
Created: created,
}
query := bson.M{
"$set": entry,
}
_, err = mongo.C(mongodb.ExampleCollection).Upsert(bson.M{
"user_id": userID,
"session_id": sessionID,
}, query)
So it inserts the document, and when updated it breaks (& mgo.LastError {Err: "Performing an update on the path '_id' would modify the immutable field '_id'", ...}), if you remove the previously generated ID, then it cannot insert it without ID.
I also read about $setOnInsert, but apparently it doesn't work like this on ID:
query := bson.M{
"$setOnInsert": bson.M{
"_id": bson.NewObjectId(),
},
"$set": entry,
}
答案1
得分: 0
在我的特定情况下,将"omitempty"添加到bson标签中对我有帮助。如果没有它,我无法在某些情况下写入没有ID的字段,因为它不会自动生成。
models.Example{
ID bson.ObjectId `bson:"_id,omitempty"`
...
}
英文:
In my specific case, adding "omitempty" to the bson tag helped me. Without it, I could not write in one of the cases without ID, it was not generated automatically.
models.Example{
ID bson.ObjectId `bson:"_id,omitempty"`
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论