Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 963
Navish Avatar asked Aug 09 '19 16:08

Navish


People also ask

Can MongoDB use part of a compound index?

MongoDB can use the intersection of indexes to fulfill queries. For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query.

What are partial indexes in MongoDB?

Partial indexes determine the index entries based on the specified filter. The filter can include fields other than the index keys and can specify conditions other than just an existence check. For example, a partial index can implement the same behavior as a sparse index: db.

How does a Mongoose model work?

Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What is an instance of a model in Mongoose?

An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.


2 Answers

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

like image 75
Liran Mery Avatar answered Oct 16 '22 11:10

Liran Mery


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

like image 32
whoami - fakeFaceTrueSoul Avatar answered Oct 16 '22 11:10

whoami - fakeFaceTrueSoul