请告诉我谁在通过 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,
}
_id自动生成。它也是一种主键。您在代码中的架构应该包含一个带有标签的字段
id,然后 mongo 会明白您需要将它用作 ObjectID。禁止使用_id,因为它是自动生成的。替换
myfield json:"id" bson:"_id"为myfield json:"id" bson:"id"