skip to Main Content

I have this code:

const database = client.db("Cluster0");
const collection = database.collection("people");

let data = { ...req.body}
let doc = collection.updateOne(
    { id: req.body.id }, 
    {$set: {}}
)

what I am trying to do is update the entire document with all the data passed from the backend. So there could be like 10 fields and if a user only updates 1 field, it will pass all 10 and update the document regardless and update all 10 fields.

How can I do this?

2

Answers


  1. const database = client.db("Cluster0");
    const collection = database.collection("people");
    
    let data = { ...req.body};
    delete data.id;
    let doc = collection.updateOne(
        { id: req.body.id }, 
        {$set: data}
    )
    

    as in this You can just pass the complete object so whatever value you will get it will update. as id is the primary key so you cannot pass it in the object so you have to remove it thats why I deleted it.

    Login or Signup to reply.
  2. You can do it without $set, example:

    let doc = collection.updateOne(
        { id: req.body.id }, 
         data
    )

    Read more about mongo updateOne: https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search