【发布时间】:2020-02-12 11:01:55
【问题描述】:
我收到了这个错误:
panic: multiple write errors: [{write errors: [{The dollar ($) prefixed field '$set' in 'conversations.newest_message.$set' is not valid for storage.}]}, {<nil>}]
这是我要更新的数据,我要更新对话中的最新消息:
{
"_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
"conversations" : [
{
"conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
"newest_message" : {
"user_name" : "",
"data" : {
"description" : "",
},
}
}
]
}
这里是 mongoldb 查询:
db.collectionA.update(
{
_id: "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
"conversations.conversation_id": "VOoHg7nY4xBcrQtzxokbM9aStSSqei44"
},
{
"$set": {
"conversations.$.newest_message": {new_update_data_here}
}
)
这里是 Golang 代码,我使用的是 mongodb 驱动程序而不是 mgo:
filter = bson.M{
"_id": id,
"conversations.conversation_id": messageReceived.ConversationID,
}
update = bson.M{
"$set": bson.M{
"conversations": bson.M{
"newest_message": newestMessage,
},
},
}
_, err = d.DB.Collection(collectionUserInformation).UpdateOne(ctx, filter, update)
if err != nil {
panic(err)
}
【问题讨论】:
-
你有哪个 mongo 版本?
-
你最后一个代码块中
newestMessage的值是多少,你确定你没有在某处设置bson.M{"$set": .....} -
@tarrsalah 我的版本是:MongoDB shell version v4.2.1
-
@topenion 我的 latest_message 变量看起来像这样,它与上面 mongodb 查询命令中的 new_update_data_here 相同:{“user_name”:“David”,“data”:{“description”:“这是消息", }, } 而且我很确定 var update 是我第一次使用 operator $set
-
@SPM 这是我向您展示整个 mongodb 查询和 Golang 代码的链接:codeshare.io/5PMjWd