'How can I use partialFilterExpression on a mongoose model

I have created a mongoose model that has an email field. I want it to be unique if a value is provided by a user but I want it to be empty is a user has not provided any value. I have found a good mongodb reference here: https://docs.mongodb.com/manual/core/index-partial/#partial-index-with-unique-constraints that could work but I don't know how to make it work on mongoose

This is how the field looks like right now

email: {
    type: String,
    index: true,
    unique: true
  }

If I leave it the way it is, I cant create multiple documents with an empty/null email field



Solution 1:[1]

In the email path level, you can use only:

email: {
  type: String
}

And in the schema level use:

SchemaName.index({ email: 1 }, {
  unique: true,
  partialFilterExpression: {
    'email': { $exists: true, $gt: '' }
  }
});

This way the unique constraint is applied only if email exists and is not an empty string

Solution 2:[2]

You can have something like :

email: {
    type: String,
    index: {
      unique: true,
      partialFilterExpression: { email: { $type: 'string' } },
    },
    default : null
  }

but do read below link, before you actually implement it, as defaults seems to work only on new document inserts :-

Mongoose v5.6.9 Documentation

Solution 3:[3]

You can use sparse

email: {
  type: String,
  unique: true,
  sparse: true
}

That way if you dont't send the email field at all mongo will not add automatically null value for the field. It will just skip it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Liran Mery
Solution 2
Solution 3 Svetlozar