I am trying to update an object inside of an array in mongoDB. But what happens is -- it returns the correct updated result, BUT it does not update the actual document in DB.
It is weird, I am using this query from past so many months and it is behaving weirdly of sudden.
Schema:
{
name: String,
donations: [
{
assigned: Boolean
}
]
}
My Query:
const updated = await DonationModel.findOneAndUpdate(
{
_id:'document Object Id',
'donations._id': 'Object Id of donation Object'
},
{
'donations.$.assigned': true,
},
{
new: true
}
);
// Here I get the updated result
// But this is NOT updated in DB.
console.log(updated);
CodePudding user response:
Try to add upsert: true
to bottem of to new: true
.
Like this:
const updated = await DonationModel.findOneAndUpdate(
{
_id:'document Object Id',
'donations._id': 'Object Id of donation Object'
},
{
'donations.$.assigned': true,
},
{
new: true,
upsert: true
}
);
// Here I get the updated result
// But this is NOT updated in DB.
console.log(updated);
CodePudding user response:
It looks as though you're missing the donations._id
in your donations object in the schema.
Also, use {upsert: true}
instead of new
, unless you mean returnNewDocument
?
Working playground example: https://mongoplayground.net/p/0bcjdi5st40
Positional update documentation is here