Wednesday 17 May 2017

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

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")},
{$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?



via Point Networks

No comments:

Post a Comment