栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Mongoose中更新数组值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Mongoose中更新数组值

你不能同时使用

$set

,并
$push

在相同的更新表达式作为嵌套的运营商。


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

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

在那里

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

要将一个新元素添加到数组中,只需一个

$push

运算符即可,例如,您可以使用
findByIdAndUpdate

update方法将修改后的文档返回为

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

使用原始

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

回调函数在其中接收参数的

(err, raw)
位置

  • err
    是错误(如果发生)
  • raw
    是蒙哥的完整回应

由于您要检查修改后的文档,因此建议您使用此

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

上面的代码会将

name
字段更新为“ foo”,并将员工ID添加到
childrens
数组中。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448620.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号