【问题标题】:Upsert issue when using mgo使用 mgo 时的更新问题
【发布时间】:2021-09-22 10:07:35
【问题描述】:

请告诉我谁在通过 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。根本不用设置,插入新文档时mongodb会为你生成一个。
  • no mongo 不会自动设置,如果结构体中没有ID,会报错:&errors.errorString{s:"ObjectIDs must be just 12 bytes long (got 0)"}
  • 不,如果 id 存在,它必须是有效的。如果您根本不设置一个,它将起作用。
  • 不,如果我将其留空,则会发生指定的错误。例如,如果记录是这样的,但是模型有ID,那么会返回错误:entry := models.Example{ UserID: userID, SessionID: sessionID, Created: created, }
  • 对不起,我只是忘记添加“omitempty”标签,然后生成ID,问题是

标签: mongodb go


【解决方案1】:

在我的具体情况下,在 bson 标签中添加“omitempty”对我有帮助。没有它,我不能在没有ID的情况下写,它不是自动生成的。

models.Example{
    ID    bson.ObjectId    `bson:"_id,omitempty"`
    ...
}

【讨论】:

    猜你喜欢
    • 2014-06-28
    • 2017-05-22
    • 1970-01-01
    • 2015-09-12
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多