如何在Mongoose中更新数组值

MMR*_*MMR 7 mongoose mongodb node.js express mean-stack

我想更新一个数组值,但我不确定正确的方法,所以我尝试了下面的方法,但没有为我工作.

我的模型,我的模型中的儿童字段

   childrens: {
       type: Array,
       default: ''
  }
Run Code Online (Sandbox Code Playgroud)

我的查询,

   Employeehierarchy.update({ _id: employeeparent._id} ,{ $set: {"$push": { "childrens": employee._id }} })
   .exec(function (err, managerparent) {});
Run Code Online (Sandbox Code Playgroud)

谁能请我帮忙.谢谢.

chr*_*dam 18

你不能同时使用$set,并$push在相同的更新表达式为嵌套运营商.

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

{
   <operator1>: { <field1>: <value1>, ... },
   <operator2>: { <field2>: <value2>, ... },
   ...
}
Run Code Online (Sandbox Code Playgroud)

哪里<operator1>, <operator2>可以来自此处指定的任何更新运算符列表.

要向数组添加新元素,单个$push运算符就足够了,例如,您可以使用findByIdAndUpdateupdate方法将修改后的文档作为

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

使用原始update()方法,语法是

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);
   }
);
Run Code Online (Sandbox Code Playgroud)

其中回调函数接收参数(err, raw)where

  • err 是否发生错误
  • raw 是Mongo的完整回复

由于您要检查修改后的文档,我建议您使用该findByIdAndUpdate函数,因为该update()方法不会为您提供修改后的文档,只是来自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);
    }
);
Run Code Online (Sandbox Code Playgroud)

以上将把name字段更新为"foo"并将员工ID添加到childrens数组中.