0

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?

4
  • what happens when you pass { $set: { name, color: undefined } in query, does it works now ? Commented Jul 22, 2022 at 16:11
  • Nope, it doesn't :( Commented Jul 22, 2022 at 16:13
  • 1
    if you really want to remove it, you have to use $unset. But I prefer using null as value instead of undefined. Commented Jul 22, 2022 at 16:25
  • But to $unset the value, I will have to first check if the color value exists or not. I thought there would be a way to do it directly with findOneAndUpdate function Commented Jul 22, 2022 at 16:31

2 Answers 2

2

As @bogdanoff indicated in the comments, you can set the value to null, not undefined.

Sign up to request clarification or add additional context in comments.

Comments

1

Since you don't want use $unset or setting that value to something else, that leaves only one way.

Use findById/findOne to fetch that Doc then modify its content then save it.

 const document = await Model.findById( req.params.id, { name: 1, color: 1 } ); //.. document.color = req.body.color || undefined //.. await document.save() 

above code works because mongoose detects change.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.