I want to delete the object where the name is "Sleep".
The code I am using:
const listName = "Holiday;
const item = new Item({
name: "Sleep"
});
User.updateOne({username : req.user.username}, {$pull:{"lists.$[updateList].items" : item}}, {
"arrayFilters": [
{"updateList.name" : listName}
]
}).exec().then(function(){
console.log("Deleted successfully");
res.redirect("/list-"+listName);
})
The mongodb object:
"_id" : ObjectId("64797ebc9e84ed9d8be3ea54"),
"username" : "[email protected]",
"lists" : [
{
"name" : "Holiday",
"items" : [
{
"name" : "Welcome to your todo-list!",
"_id" : ObjectId("647988267f3ddfc2982f7d77")
},
{
"name" : "Click + to add another item.",
"_id" : ObjectId("647988267f3ddfc2982f7d78")
},
{
"name" : "<-- Click this to delete an item.",
"_id" : ObjectId("647988267f3ddfc2982f7d79")
},
{
"name" : "Sleep",
"_id" : ObjectId("64799279c3da415dc4ce7574")
},
{
"name" : "WakeUp",
"_id" : ObjectId("6479930e6d49e494aad1dffa")
}
],
"_id" : ObjectId("647988357f3ddfc2982f7d85")
}
]
}
It seems there is some problem with the updateOne and $pull: attributes but I can’t figure out what.
2
Answers
Try with
I have tested this code, it’s working fine.
Note: just write object id in findOne({_id}) function. No need to edit
it. Use this code inside asyn function