請告訴我誰在通過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: “在路徑'_id'上執行更新將修改不可變字段'_id'”,...}),如果刪除以前生成的ID,則它無法在沒有ID的情況下插入它。我也讀到$setOnInsert,但顯然它在ID上不是這樣工作的:query := bson.M{ "$setOnInsert": bson.M{ "_id": bson.NewObjectId(), }, "$set": entry,}
1 回答

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
在我的特定情況下,在bson標簽中添加“omitempty”對我有所幫助。沒有它,我無法在沒有ID的情況下寫入其中一個,它不是自動生成的。
models.Example{ ID bson.ObjectId `bson:"_id,omitempty"` ... }
- 1 回答
- 0 關注
- 88 瀏覽
添加回答
舉報
0/150
提交
取消