I am having trouble in deleting all elements from an array in mongodb. This is my schema:
const userSchema=mongoose.Schema({
name: String,
email: String,
password: String,
blog: [{
date: Date,
post: String
}],
week: [{
weekday: String,
tasks:[String]
}],
todo: [String]
});
const User= mongoose.model("User", userSchema);
I want to delete all data from todo but it is not working. Here is the code for that:
app.post("/deletelist",(req,res) =>{
console.log(req.body);
const user = req.body.userid;
console.log(user);
// User.find({_id: user}, async function(err, foundUser){
// if(err){
// console.log(err);
// } else{
// foundUser.updateOne({},{ $set : {"todo": [] }} , {multi:true});
// // await foundUser.save();
// res.send("ToDo Deleted");
// }
// });
User.updateOne({_id:user},{ $set : {"todo": []}}, {multi:true});
res.send("ToDo Deleted");
});
I am getting user from the frontend. The part that is commented and the other one(User.updateOne) both are not working. I'll be glad if anyone can help
this will remove all the elements even the key if you want to remove the elements only try @Abdelrhman answer
User.updateOne({_id:user},{$unset:{todo:""}})
You cannot use multi-option in the updateOne method remove it and it will work
Example
User.updateOne({_id:user},{ $set : {"todo": []}})