0

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

Akshat
  • 65
  • 8
  • 1
    `array.length = 0;` – ControlAltDel Feb 15 '22 at 18:01
  • I think the issue is that `{ $set: {"todo": [] } }` will not do anything because it's already an array and you don't provide specific values. I think I had this issue on one of my side projects. I ended up doing something like `{ $unset: {"todo": true } }` and right after this I called `{ $set: {"todo": [] } }`, but be careful because this operation is not atomic – Tim Nimets Feb 15 '22 at 18:11
  • @TimNimets is there any other way to do that? – Akshat Feb 15 '22 at 18:18
  • @Akshat I have found this code on the internet which looks prettier. `db.users.update({username: "tom"}, {$pull: {documents: {$exists: true}}})` you should try both. Also this issue is not directly from mongodb, but most likely from mongodb node driver, since manual updates in the console seem to works for me. – Tim Nimets Feb 16 '22 at 02:57

2 Answers2

1

Updated

You cannot use multi-option in the updateOne method remove it and it will work

Example

User.updateOne({_id:user},{ $set : {"todo": []}})
1

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:""}})
Super sub
  • 269
  • 2
  • 8