Search code examples
mongodbmongoosemongoose-schema

How to update a value in a array of nested object in Mongoose(Momgodb)?


{ 
    "_id" : ObjectId("6221f3a818880f14e3c33040"), 
    "__v" : 0, 
    "createdAt" : ISODate("2022-03-04T11:10:32.753Z"), 
    "pm" : { 
        "checkList" : [ 
            { 
                "ch_id" : "621eff4e0ed5c751adaa42fb", 
                "status" : "statu", 
                "dateMonthYear" : 1646286480139.0, 
                "val" : "Gopi", 
                "remarks" : "Good", 
                "_id" : ObjectId("6221f3a80a703519a4406e6c") 
            }, 
            { 
                "ch_id" : "621eff4e0ed5c751adaa42fb", 
                "status" : "status", 
                "dateMonthYear" : 1646286480139.0, 
                "val" : "Gopi", 
                "remarks" : "Good", 
                "_id" : ObjectId("6221f3a80a703519a4406e6e") 
            } 
        ] 
    }, 
    "updatedAt" : ISODate("2022-03-04T11:56:59.662Z") 
}

Above is the collection, and in that I need to update the checklist array inside pm object using "_id" as a find condition. For example I need to change val and remarks of _id, ObjectId("6221f3a80a703519a4406e6e").

How to achieve this?


Solution

  • You can update a value in an array of nested objects in Mongoose
    
    `db.users.update({"pm.checkList.ch_id" : "621eff4e0ed5c751adaa42fb"},{ $set:{
       "pm.checkList.$.val" : "nop",
       "pm.checkList.$.remarks" : "bed",
    }})`