4

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.

ET-CS
  • 6,334
  • 5
  • 43
  • 73
  • If you really want to remove data/field from and document/object i would suggest to use `$unset` operator. For more detail check here https://docs.mongodb.com/manual/reference/operator/update/unset/ – Ankur Nov 30 '20 at 09:45

1 Answers1

9

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.

Javier Bonilla
  • 106
  • 1
  • 5
  • By the way, as far as I can tell this is a Mongoose feature, so you can't use it if you are using the native MongoDB driver – szeb Apr 07 '21 at 15:39
  • 1
    That's true szeb, I should remark that is only a solution with Mongoose. It was be an option on the user question but not the single option, thanks. – Javier Bonilla Apr 15 '21 at 16:58
  • With mongoose version 6+ you no longer can or want to use "omitUndefined" option. Mongoose removes `undefined` values instead of coercing them to `null`. More details here https://mongoosejs.com/docs/migrating_to_6.html#removed-omitundefined – Dmitry Shvetsov Aug 30 '22 at 12:24