How to update schema without one object in mongoose

Viewed 42

I want to update my schema without one object.

When i updated my schema the req.body automaticly updating schema with $set. But i want to prevent update all schema. For example req.body can include user role and this case i don't want to update user role.

User.findOneAndUpdate(
 { _id: req.user._id },
 { $set: req.body },
 { new: true, runValidators: true },
)

So i want to update all body without role object in user schema.

1 Answers

Well to do that you can so this

User.findOne({ _id: req.user._id },(err,user)=>{
       if(err) throw err; 
       user.FieldYouWantToUpdate = req.body.name // likewise add your values

       // then save the document
       user.save();
     });

In here you can have more control to yourself when doing an update using mongoose. What heppens is you query using a user id and get a user. so that user object can be accessed within the callback of the findOne() function. After that using the user object you can alter the user as you want may it be a single field, 2 fields, all fields what ever you like. You can have the full control over update

Related