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" : "aryan@gmail.com",
"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.
Try with
const listName = 'Holiday';
User.updateOne(
{ username: req.user.username, 'lists.name': listName },
{ $pull: { 'lists.$[].items': { name: 'Sleep ' } } }
)
.exec()
.then(function () {
console.log('Deleted successfully');
res.redirect('/list-' + listName);
});