在使用mgo时出现了upsert问题。

huangapple go评论76阅读模式
英文:

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"`
    ...
}

huangapple
  • 本文由 发表于 2021年9月22日 18:07:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/69282144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定