首页 > 解决方案 > 使用节点 js 中的 findOneAndUpdate 更新数组中的对象

问题描述

我在 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);
    }
);

标签: node.jsmongodbmongoose

解决方案


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);
    }
);

推荐阅读