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

131
Views
How to add item to an array in Mongodb?

I am having trouble in appending data into 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 add data to todo but it is not working. Here is the code for that:

app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;
    
    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            foundUser.save();
            res.send("ToDo Updated");
        }
    });
});

I am getting user and item from the frontend. When I am console logging foundUser then I am getting the user but I am not able to add item to it.

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

0

It's cause the save() is an async method, try using await

app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;
    
    console.log(user);
    console.log(item);
    User.findOne({_id: user}, async function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            await foundUser.save();
            res.send("ToDo Updated");
        }
    });
});
about 4 years ago · Juan Pablo Isaza Report

0

app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;
    
    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            await User.updateOne({ _id: foundUser._id }, { $set: foundUser });  
            res.send("ToDo Updated");
        }
    });
});

Another approach

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!