0

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.

2 Answers 2

1

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");
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.