如何更新猫鼬中的数组值 [英] How to update a array value in Mongoose

查看:33
本文介绍了如何更新猫鼬中的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新一个数组值,但我不确定这样做的正确方法,所以我尝试了以下方法但对我不起作用.

I want to update a array value but i am not sure about the proper method to do it ,so for i tried following method but didnt worked for me.

我的模特,我模型中的 children 字段

My model, The children field in my model

   childrens: {
       type: Array,
       default: ''
  }

我的查询,

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

谁能帮我.谢谢.

推荐答案

不能同时使用 $set$push 在与嵌套运算符相同的更新表达式中.

You can't use both $set and $push in the same update expression as nested operators.

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

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

其中 , 可以来自指定的任何更新操作符列表 此处.

where <operator1>, <operator2> can be from any of the update operators list specified here.

要向数组添加新元素,只需一个 $push 运算符就足够了,例如您可以使用 findByIdAndUpdate update 方法将修改后的文档返回为

For adding a new element to the array, a single $push operator will suffice e.g. you can use the findByIdAndUpdate update method to return the modified document as

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

使用您原来的update() 方法,语法为

Using your original update() method, the syntax is

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) where

in which the callback function receives the arguments (err, raw) where

  • err 是发生的错误
  • raw 是来自 Mongo 的完整响应
  • err is the error if any occurred
  • raw is the full response from Mongo

既然你想查看修改后的文档,我建议你使用findByIdAndUpdate 函数自 update() 方法不会给你修改后的文档,只会给你 mongo 的完整写入结果.

Since you want to check the modified document, I'd suggest you use the findByIdAndUpdate function since the update() method won't give you the modified document, just the full write result from mongo.

如果你想更新文档中的一个字段并同时将一个元素添加到数组中,那么你可以这样做

If you want to update a field in the document and add an element to an array at the same time then you can do

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 数组中.

The above will update the name field to "foo" and add the employee id to the childrens array.

这篇关于如何更新猫鼬中的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆