how to update child array and parent element both at the same time using mongoose?

2k Views Asked by At

Look at my following example schema.

const ParentSchema = new mongoose.Schema({
    id:String
    name:String
    age:Number
    child:[{
        id:String,
        name:String,
        age:Number}]
    })

const collectionName = mongoose.model("parent", ParentSchema)

Now I want to increase the age of child and parent for the specific id of each of them. both at the same time. I tried doing it with the following query

collectionName.update({'_id':new mongoose.Types.ObjectId("59198a3e73ae303f97e97e8f"),'child._id':new mongoose.Types.ObjectId("59198a3e73ae303f97e97eds")},
{$inc:{'age':1},$inc:{'child.$.age':1}},function(err,res){
    if(err){
        console.log(err.message)
    }else{
console.log(res)
}

Above query worked well but it only updated the child age and not the parent one. Now I'm not sure how should I mould my query to update both?

1

There are 1 best solutions below

4
Gianmarco On BEST ANSWER

This query work for me:

db.collection.update({
    '_id': new mongoose.Types.ObjectId("59198a3e73ae303f97e97e8f"), 
    'child.id': A SPECIFIC ID 
}, 
{ 
    $inc: { 'age': 1, 'child.$.age': 1 }
});

Your query doesn't work because the $ operator need a condition to verify before increase the appropriate child from the nested array. If you want to go deepen, here is the official documentation.