【问题标题】:MongoDB The dollar ($) prefixed field '$unset' in '$unset' is not valid for storage errorMongoDB '$unset' 中的美元 ($) 前缀字段 '$unset' 对存储错误无效
【发布时间】:2016-04-29 10:21:45
【问题描述】:

我正在尝试使用适用于 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)

我做错了什么?我确信在执行命令时文档中都存在这两个字段,那么我该如何解决这个错误? (是的,它肯定连接到服务器)

【问题讨论】:

    标签: node.js mongodb mongodb-query


    【解决方案1】:

    如果要修改字段值,则需要使用$set 运算符。

    db.collection("myCollection").updateOne({ "_id": "testDocument" },
        { 
            "$set": { "val1": "newval" }, 
            "$unset" : { "val2": "" } 
        }, function(err, result){
            // dosomething()
    })
    

    【讨论】:

    • 我在 使用 $set 时遇到了同样的错误:collection.updateMany({ approved: false }, { $set: { status: NumberInt(1), $unset: { approved: '' } } })。原来我错误地嵌套了大括号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2019-12-27
    • 2023-03-27
    • 2017-12-13
    • 2020-09-23
    相关资源
    最近更新 更多