Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, update values in array of objects

People also ask

How do you update data in an array of objects in MongoDB?

Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator. You must include the array field as part of the query document.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.

What is $Push in mongoose?

$push. The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

How do you use findByIdAndUpdate?

This id is passed inside the findByIdAndUpdate() function and then it simply grabs the document matching that particular id. After getting the document with that matching id, it simply updates the data inside the document. What needs to be updated inside the document is specified in the function as an argument.


You're close; you should use dot notation in your use of the $ update operator to do that:

Person.update({'items.id': 2}, {'$set': {
    'items.$.name': 'updated item2',
    'items.$.value': 'two updated'
}}, function(err) { ...

model.update(
    { _id: 1, "items.id": "2" },
    {
        $set: {
            "items.$.name": "yourValue",
            "items.$.value": "yourvalue",
         }
    }
)

MongoDB Document


There is a mongoose way for doing it.

const itemId = 2;
const query = {
  item._id: itemId 
};
Person.findOne(query).then(doc => {
  item = doc.items.id(itemId );
  item["name"] = "new name";
  item["value"] = "new value";
  doc.save();

  //sent respnse to client
}).catch(err => {
  console.log('Oh! Dark')
});

There is one thing to remember, when you are searching the object in array on the basis of more than one condition then use $elemMatch

Person.update(
   {
     _id: 5,
     grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
   },
   { $set: { "grades.$.std" : 6 } }
)

here is the docs


For each document, the update operator $set can set multiple values, so rather than replacing the entire object in the items array, you can set the name and value fields of the object individually.

{'$set':  {'items.$.name': update.name , 'items.$.value': update.value}}