Updating multiple fields within single document

How to update multiple fields in a single document

Whenever I try to update multiple fields only one values gets changed irrespective of how many changes I made in my form

export const updateEmployee=async(req,res)=>{
        const {FirstName,LastName,Email,Password,Mobile,ReportingManager,EmployeeCode,Salary,Location,Country,State,Department,
        const _id=req.params.id;
        const updatedResult=await PostMessage.updateOne({_id},
        console.log('data was updated',updatedResult);

I have used findByIdandUpdate() method too but same result

Are you using an abstraction layer, like mongoose? Probably since you

I ask because when I try your code I get an error.

c.updateOne( { _id } , { First , Last } , { new : true })
MongoInvalidArgumentError: Update document requires atomic operators

This is expected as you are missing an operator like $set.

The new:true option is not one that I recognize for MongoDB nodejs driver.

If using pure MongoDB driver try with the following as the 2nd parameter of updateOne().

{ "$set" : 
  { FirstName,  LastName,  Email, /* ... */ }
1 Like

Hii Steevej !!
Yes I am using mongoose, its a mern app could you tell how do i resolve this issue if using moongose?

new:true option I saw it on a youtube tutorial in the creator’s video any suggestions how can I solve this issue to update multiple fields in a single document when using moongose also

I know nothing about Mongoose. I try to stay away from abstraction layers. Hopefully, someone with mongoose experience will jump it. Other you may try a mongoose specific forum if such a thing exists. There is always stackoverflow.