MongoDB Nodejs在更新时插入错误

时间:2018-03-20 08:40:02

标签: node.js mongodb express

我使用upsert选项,因此将插入不存在的项目,但是我收到此错误,它在我更新现有项目时工作正常

MongoError: The positional operator did not find the match needed from the query. Unexpanded update: options.$.votes

此处更新

 db.collection('polls').update(
               { _id:  require("mongodb").ObjectId(id), "options.key": item },
               { $inc: { "options.$.votes" : 1 } }, 
               {upsert: true, safe: false},
               function(err, data){
                   if(err) throw err;

                   if(data){
                       console.log(data)
                   }
               }
            )

以下是示例数据

{
    "_id": {
        "$oid": "5aae26203ab1cc0f15e43dc6"
    },
    "author": "me",
    "title": "fruits you love the most",
    "options": [
        {
            "key": "banana",
            "votes": 4
        },
        {
            "key": "apple",
            "votes": 6
        },
        {
            "key": "mango",
            "votes": 11
        },
        {
            "key": "grapes",
            "votes": 6
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

来自this。您无法将$upsert操作一起使用。

我认为您需要2个单独的查询来检查options.key在使用更新查询进行投票之前是否存在$inc。或$push如果它不存在则排列。