I'm sorry if the title is a bit confusing, but I'm not sure how to re-phrase it.
So I have the following object:
{
"_id": "622dec2e037d7ae286b366c9",
"name": "Moriel Odeski",
"email": "moriel96@gmail.com",
"street": "Ben Gurion",
"city": "Be'er Sheva",
"zipcode": 329886,
"tasks": [
{
"id": "1",
"title": "Test",
"completed": true
},
{
"id": "2",
"title": "Test2",
"completed": false
},
{
"id": "3",
"title": "Test3",
"completed": false
},
{
"id": "4",
"title": "Do The Dishes",
"completed": false
}
],
"posts": [
{
"id": 1,
"title": "That's Moriel's Post",
"body": "According to my evaluations 0-0"
},
{
"id": 2,
"title": "Something about something",
"body": "That's interesting"
}
]
}
I'm trying to write a function that gets a userID and a taskID and by calling it, it changes the .completed of the task to true where id = taskID and where userId : userID
I have the following function that doesn't work:
const markTaskCompleted = (userID , taskID) =>
{
return new Promise((resolve, reject) =>
{
User.findOneAndUpdate({id : userID , tasks : {$elemMatch: {id : taskID}}},
{$set: {"tasks.$.completed" : true}},
{"new" : true , "safe" : true , "upsert" : true} , function(err , data)
{
if(err){reject(err)}
else
{
resolve(data.tasks)
}
})
})
}
It throws :
Plan executor error during findAndModify :: caused by :: The positional operator did not find the match needed from the query.
Where did I go wrong with this?
I feel difficult to read your code because it doesn't look clean.. so maybe first it's better to make it cleaner.. I guess?
const markTaskCompleted = async (userID , taskID) => await User.findOneAndUpdate({
id: userID,
tasks: {$elemMatch: {id: taskID}}
},
{$set: {"tasks.$.completed": true}},
{"new": true , "safe": true , "upsert": true},
})
You used callback inside callback so it didn't look clean to me.
I used async/await. I hope this looks cleaner to you too.
The official mongoose document also uses await for findOneAndUpdate() method.
https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-started
Check it out. Can you check if the code I wrote works?