Search code examples
node.jsmongoosenullundefinedfindoneandupdate

Mongoose findOneAndUpdate with undefined set as null


I have problem understanding findOneAndUpdate with undefined and null.

when creating an object:

const user = new User({
   _id: 1,
   name: "foo",
   address: undefined
});
user.save()

It's creating a new document with only name and no address:

{
   name: "foo"
}

If I'm using the same logic with findOneAndUpdate after:

findOneAndUpdate({_id: 1}, {
   name: "bar",
   address: undefined
});

the document in the database will now contain a null for address:

{
   name: "bar",
   address: null,
}

Which I can't understand why.

I would expect that when I set a value to undefined it should remove the current item, So if I had for example a document with address: "somewhere", or even without address at all, I expect that setting undefined should remove it (or not set if wasn't there), instead of set it to null.

Is this something I can achieve somehow? or is this the behavior of findOneAndUpdate? mongodb? (or mongoose?)

Thanks in advance, Etay.


Solution

  • Yeah, this is because the method findOneAndUpdate have an attribute option that can´t avoid the undefined variables from an object and set a null value by default. To fix this, you only pass the option "omitUndefined: true" because by default is false. An example of code to apply:

        await this.yourModel.findByIdAndUpdate(
                object._id,
                object,
                {
                  new: true,
                  omitUndefined: true
                },
              )
    

    This solution is only available with Mongoose.