Home > database >  How to add item to an array in Mongodb?
How to add item to an array in Mongodb?

Time:02-11

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.

CodePudding user response:

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");
        }
    });
});

CodePudding user response:

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

  • Related