Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

node.js - How to update a array value in Mongoose

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.

My model, The children field in my model

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

My query,

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

Can anyone please provide me help.Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

The correct syntax for using the update operators follows:

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

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

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

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

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

  • err is the error if any occurred
  • raw is the full response from 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);
    }
);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...