Atomic Operators needed when updating document

app.patch('/update', async(req, res) => {
    await client.connect();
    db = await client.db("Lab3");
    let collection = await db.collection("students");
    let susername = req.body.username

    let result = await collection.findOneAndUpdate(
        {username : susername}, req.body, {new: true}
    )

    res.send(result).status(200);
});

Hi everyone, I’m currenly facing a problem when I want to update data to my mongoDB database. I try to not specified what to update from the user, but let the user choose what to update. So that my findOneandUpdate parameter will be username as filter, req.body as the content to update to the database. Can anyone help me to solve this problem? Thank you so much!

Hello @WoNGG,

Can you please share the error you are getting?

I can see you missed the set stage name in the update part, it should be,

{ $set: req.body }

Note: Make sure you filter the properties before updating the database, otherwise it will increase the junk data those are not useful in the future.

3 Likes

Hello, @turivishal. The error before I get is [Update document requires atomic operators]. After I entering the $set parameter, the program works successfully! Thanks for your helping, I have find for the way to solve this error for hours.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.