使用节点js中的findOneAndUpdate更新数组中的对象

时间:2018-09-02 19:56:40

标签: node.js mongodb mongoose

我在mongodb中有此数据,我想用一个查询更新它:

{ 
"_id" : ObjectId("zzzzz6e57fss8ssb9cssbsss"), 
"user" : "zzzz", 
"data" : [
    {
        "_id" : ObjectId("zzzzz6e57ffe8b2b9c77b6b9"),  
        "me" : "LLL"
    }, 
    {
        "_id" : ObjectId("5b8ab719406d7235240f4338"), 
        "me" : "III"
    }
]
"__v" : NumberInt(0)
}

并且我想通过 findOneAndUpdate 更改'me':'III' 该代码无效。

var ObjectID = require('mongodb').ObjectID;
var o_id = new ObjectID("5b8ab719406d7235240f4338");
array.findOneAndUpdate
(
    { 'data._id' : o_id    },
    {  $set:{'me' : "Stackoverflow"    }   }, 
    function (error, success) 
    {
        if (error) console.log(error);
        if(success == null )
            console.log("nullllllllllllllllllllllll");
        console.log(success);
    }
);

1 个答案:

答案 0 :(得分:1)

var ObjectID = require('mongodb').ObjectID;
var o_id = new ObjectID("5b8ab719406d7235240f4338");
array.findOneAndUpdate
(
    { 'data._id' : o_id    },
    {  $set:{'data.$.fr' : "Stackoverflow"    }   }, 
    function (error, success) 
    {
        if (error) console.log(error);
        if(success == null )
            console.log("nullllllllllllllllllllllll");
        console.log(success);
    }
);
相关问题