If value of a property is null when updating then that property should not be added to the record
I wouldn't write this this way, but I'll tell you why your code is failing.
The problem is your $set block
you're choosing to specifically set the value to the update object passed in. If the value is undefined
you're forcing mongo to set that to null.
Here's the problem
example, in DB:
{
"_id" : ObjectId("ns8f9yyuo32hru0fu23oh"),
"name" : "firstTest",
"nickname": "jack",
"__v" : 0
}
IF you pass in testToUpdate = { name: 'foo' }
you'll end up with
Test.update({ ... }, { $set: { name: 'foo', nickname: undefined }}
because you're getting updatedValues.nickname
off of the arguments and thats not defined
what you WANT is
Test.update({ ... }, { $set: updatedValues }
which is translates to Test.update({ ... }, { $set: { name: 'foo' } }
.
You're no longer providing a key for nickname, thus not making it set to undefined/null.
I would use a mongoose plugin and not worry about manually passing the fields all the way to your model
see https://github.com/autolotto/mongoose-model-update
you can define the update-able fields and then you can just do
model.update(req.body)
and not worry about all this
Even if you don't want to use the plugin you can still just do
Test.findByIdAndUpdate(id, { name, nickname }, callback)