如何在Mongoose中更新数组值
我想更新一个数组值,但我不确定要执行的正确方法,因此我尝试了以下方法,但没有为我工作。
我的模型,我模型中的子域
   childrens: {       type: Array,
       default: ''
  }
我的查询
   Employeehierarchy.update({ _id: employeeparent._id} ,{ $set: {"$push": { "childrens": employee._id }} })   .exec(function (err, managerparent) {});
谁能给我帮助。谢谢。
回答:
你不能同时使用
,并
在相同的更新表达式作为嵌套的运营商。
使用更新运算符的正确语法如下:
{   <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)位置
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数组中。
以上是 如何在Mongoose中更新数组值 的全部内容, 来源链接: utcz.com/qa/432525.html

