Search code examples
javascriptnode.jstypescriptexpressmongoose

Mongoose unset field of document through findByIdAndUpdate()


I am sending my documents through expressjs to my server and then update the document by using the request body which comes as JSON (partial document) and passing it to the findByIdAndUpdate() function.

Earlier by using null as a field value of the document the field got removed. So far, so good, but now I am facing the issue that it is not working anymore.

What can I do in that case?

My Schema:

const personSchema = new Schema<IPerson>(
  {
    name: String,
    age: Number
  }
);

My initial document:

{
  name: 'Maxwell',
  age: 30
}

My document used in findByIdAndUpdate():

{
  name: 'Jane Doe',
  age: null
}

The final document:

{
  name: 'Jane Doe',
  age: null
}

The document I've expected:

{
  name: 'Jane Doe'
}

Solution

  • I finally figured it out by myself.

    For me, it was working in Mongoose v5, and now with v7, I face that issue. From v5 to v6, the option omitUndefined was removed, and that changed the behavior.

    Reference: https://mongoosejs.com/docs/migrating_to_6.html#removed-omitundefined

    It seems I have to live with it, but I would highly appreciate it if someone has a solution/workaround to still allow the removal of fields in documents without aggragation.