Home > front end >  Mongoose how do we update nested objects
Mongoose how do we update nested objects

Time:09-26

I am trying to update nested object using mongoose. I am trying to update the "remindTime date" only and keep the "time" I can update the "remindTime date" however it erases my "remindTime time" property.

I have try the following and none of them work

Model.updateMany(req.query, { remindTime: { date: "2021-09-28" } })

Model.updateMany(req.query, { remindTime: $set:{ { date: "2021-09-28" } } } )

Database data that I am updating

{
    "_id": {
        "$oid": "614d3cedfb2600340fdb28f9"
    },
    "date": "2021-09-23",
    "title": "First test",
    "description": "not working yet",
    "remindTime": {
        "date": "2021-09-28",
        "time": "01:20 am"
    },
    "isComplete": false,
}

CodePudding user response:

You can use dot notation:

According to docs:

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

To specify or access a field of an embedded document with dot notation, concatenate the embedded document name with the dot (.) and the field name, and enclose in quotes:

"<embedded document>.<field>"

So the query:

Model.updateMany(req.query,
{
  "$set": {
    "remindTime.date": "new date"
  }
})

Example here

CodePudding user response:

Please try this:

Model.updateMany(req.query, { "remindTime.date": "2021-09-28"})
  • Related