Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
What is the proper way to delete all elements from an array?

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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:""}})
about 4 years ago · Juan Pablo Isaza Report

0

Updated

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

Example

User.updateOne({_id:user},{ $set : {"todo": []}})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!