I'm trying to update a schema values based on user input.
My schema is:
({ name: { type: String, required: true, }, color: { type: String, }, createdAt: { type: Date, default: Date.now, }, }); The name field is required however the color field is optional. So, supposing the user created a document:
{ "name": "Blue", "color": "#20387d" } he can then edit the same document where he doesn't provide the color value:
{ "name": "Blue" } My code for update is:
const { name, color} = req.body; const document = await Model.findOneAndUpdate( { _id: req.params.id, }, { $set: { name, color }}, { new: true } ); This should update color value to undefined in my MongoDB. However, the color remains same as provided initially whereas the name updates. I want the color to change to undefined if its not provided by the user. How do I do that?
{ $set: { name, color: undefined }in query, does it works now ?$unset. But I prefer usingnullas value instead ofundefined.$unsetthe value, I will have to first check if thecolorvalue exists or not. I thought there would be a way to do it directly withfindOneAndUpdatefunction