mongoose update array code example

Example 1: mongoose modify all elements in array

// Playground: https://mongoplayground.net/p/-TgGWwBd5l-
db.collection.update({
  "_id": "password"
},
{
  "$inc": {
    "waitlist.$[].queue_place": -1
  }
})

// Database
/*
[
  {
    "_id": "password",
    "waitlist": [
      {
        "_id": "adasd",
        "queue_place": 123
      },
      {
        "_id": "ada43sd",
        "queue_place": 2
      }
    ]
  }
]
*/

Example 2: mongoose save or update

// This will create another document if it doesn't exist
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });

Example 3: mongoose updatemany example

User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});

Example 4: updating an array of object in mongoose

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

Example 5: update query in mongoose

var conditions = { name: 'bourne' } 
  , update = { $inc: { visits: 1 }}

Model.update(conditions, update, { multi: true }).then(updatedRows=>{
  
}).catch(err=>{
  console.log(err)
  
})

Example 6: mongoose update array in object

Person.findOneAndUpdate({_id: id}, 
{ 
  "$set": {[`items.$[outer].${propertyName}`]: value} 
},
{ 
  "arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
  ...
})