Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 963
MMR Avatar asked Jan 06 '17 08:01

MMR


People also ask

How do I update an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do you update an array?

To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values. Copied! const arr = ['zero', 'one', 'two']; arr.

How do you update an array in node JS?

To update the first array element of each document that matches your query, use the positional operator $ . The positional operator $ references the array matched by the query. You cannot use this operator to reference a nested array.

How do I add values to an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.


3 Answers

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.

like image 69
chridam Avatar answered Nov 01 '22 18:11

chridam


can follow this

if childrens contains string values then model can be like:

childrens: [{
    type : String
}]

if childrens contains ObjectId values of another collection _id and want populate then model can be like:

childrens: [{
    type : mongoose.Schema.Types.ObjectId,
    ref: 'refModelName'
}]

no need to use $set just use $push to insert value in childrens array. so query can be like:

Employeehierarchy.update(
   { _id: employeeparent._id},
   {"$push": { "childrens": employee._id } }
 ).exec(function (err, managerparent) {
    //
 });
like image 35
Shaishab Roy Avatar answered Nov 01 '22 19:11

Shaishab Roy


This will help I guess

Employeehierarchy.findOneAndUpdate(
  { _id:employeeparent._id },
  { $set: { "childrens": employee._id }}
)
like image 40
Deeksha Sharma Avatar answered Nov 01 '22 17:11

Deeksha Sharma