how to update array value in mongoose and nodejs 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 update array in object
Person.findOneAndUpdate({_id: id},
{
"$set": {[`items.$[outer].${propertyName}`]: value}
},
{
"arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
...
})