Home > Software design >  update all fields mongodb node.js
update all fields mongodb node.js

Time:11-26

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?

CodePudding user response:

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.

CodePudding user response:

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/

  • Related