您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Mongoose中更新数组值

如何在Mongoose中更新数组值

你不能同时使用 ,并 在相同的更新表达式作为嵌套的运营商。

使用更新运算符的正确语法如下:

{
   <operator1>: { <field1>: <value1>, ... },
   <operator2>: { <field2>: <value2>, ... },
   ...
}

在那里<operator1>, <operator2>可以来自任何指定的更新列表运营商的位置

要将一个新元素添加到数组中,只需一个 运算符即可,例如,您可以使用 update方法修改后的文档返回为

Employeehierarchy.findByIdAndUpdate(employeeparent._id,
    { "$push": { "childrens": employee._id } },
    { "new": true, "upsert": true },
    function (err, managerparent) {
        if (err) throw err;
        console.log(managerparent);
    }
);

使用原始 方法,语法为

Employeehierarchy.update(
   { "_id": employeeparent._id},
   { "$push": { "childrens": employee._id } },
   function (err, raw) {
       if (err) return handleError(err);
       console.log('The raw response from Mongo was ', raw);
   }
);

回调函数在其中接收参数的(err, raw)位置

由于您要检查修改后的文档,因此建议您使用此 函数,因为该 方法不会提供修改后的文档,而只会提供mongo的完整写入结果。

如果要更新文档中的字段并将元素同时添加到数组中,则可以执行

Employeehierarchy.findByIdAndUpdate(employeeparent._id,
    { 
        "$set": { "name": "foo" },
        "$push": { "childrens": employee._id } 
    } 
    { "new": true, "upsert": true },
    function (err, managerparent) {
        if (err) throw err;
        console.log(managerparent);
    }
);

上面的代码会将name字段更新为“ foo”,并将员工ID添加childrens数组中。

mongodb 2022/1/1 18:15:29 有277人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶