我正在尝试使用MongoDB的Node.js驱动程序更新文档
我正在执行两个操作,一个修改字段的值,另一个删除字段,我正在使用的代码如下:
db.collection("myCollection").updateOne({_id: "testDocument"}, {val1:"newval",$unset:{val2:""}}, function(err, result){
//Code that logs the error
因此记录了错误并产生错误代码52和以下堆栈跟踪:
MongoError: The dollar ($) prefixed field '$unset' in '$unset' is not valid for storage.
at Function.MongoError.create (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
at toError (/home/ubuntu/workspace/node_modules/mongodb/lib/utils.js:114:22)
at /home/ubuntu/workspace/node_modules/mongodb/lib/collection.js:1008:67
at commandCallback (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1161:9)
at Callbacks.emit (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at messageHandler (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:295:23)
at Socket.dataHandler (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:285:22)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:146:16)
我做错了什么?我确信在执行命令时文档中存在两个字段,那么如何修复此错误? (是的,它肯定连接到服务器)
答案 0 :(得分:2)
如果要修改字段值,则需要使用$set
运算符。
db.collection("myCollection").updateOne({ "_id": "testDocument" },
{
"$set": { "val1": "newval" },
"$unset" : { "val2": "" }
}, function(err, result){
// dosomething()
})