Database
{
"followings": [],
"post": [],
"saved": [],
"tagged": [],
"_id": "637661a7454b5127be5baeb4",
"username": "shiv_yadav",
"password": "12345",
"emailorphone": "99999",
"name": "Shiv Yada",
"Saved": [],
"Tagged": [],
"__v": 0,
"bio": "test newBiofssx",
"profileimg": "http://localhost:4100/images/637661a7454b5127be5baeb4-shiv_yadav-1670158119497-jan-kopriva-pfsNJ0wUT5E-unsplash.jpg",
"email": "[email protected]",
"gender": "Male",
"notification": [
{
"notiticationId": "1672147216504",
"type": "RequestedToFollow",
"requester": {
"_id": "637722bdd78bd1ecef887b44",
"username": "vik_choudhar",
"profileimg": "http://localhost:4100/images/637722bdd78bd1ecef887b44-vik_choudhary-1670321337541-pexels-bess-hamiti-35188.jpg",
"name": "Vikash"
},
"readed": false
},
{
"notiticationId": "1672201273818",
"type": "RequestedToFollow",
"requester": {
"_id": "63772408d78bd1ecef887b47",
"username": "Jay_B",
"profileimg": null,
"name": "Jay"
},
"readed": false
},
{
"notiticationId": "1672201356611",
"type": "RequestedToFollow",
"requester": {
"_id": "6377244ad78bd1ecef887b4a",
"username": "Urvesh_V",
"profileimg": null,
"name": "Urvesh"
},
"readed": false
}
],
}
I am using a mongoose. I have a record of users. I am making the notification feature. I have an array of objects for notification fields. I want to update the notification status (Here the field "readed") for id(1672147216504,1672201273818) from false to true of any particular user. Here id means the time field in the object. I have read the document, but it's not updated when I update the field.
I don't know where I am making a mistake.
Can anyone tell me how I can do that? I have tried the following code.
const notiticationIds = [1672147216504, 1672201273818]
const data = await user.findOneAndUpdate(
{ _id: userid, 'notifications.notiticationId': notiticationIds }, {
'$set': {
'notifications.$.readed': 'true',
}
})
CodePudding user response:
One option is to use $[<identifier>]
in order to choose the specific items to update inside the array. If you want to get back the document after the update (this is not the default), use returnNewDocument
: true
const data = await user.findOneAndUpdate(
{_id: userid,
notification : {
$elemMatch: {
notiticationId: {$in: ["1672147216504", "1672201273818"]}
}
}},
{$set: {"notification.$[item].readed": true}},
{
arrayFilters: [{"item.notiticationId": {$in: ["1672147216504", "1672201273818"]}}],
returnNewDocument: true
}
)
See how it works on the playground example