Navish
Navish

Reputation: 119

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

Upvotes: 10

Views: 11158

Answers (4)

Anuj Saraswat
Anuj Saraswat

Reputation: 1

Try creating TTL index for field topic which matches with value DTC and PDM.

After running this command, new TTL index will be created with name as test_index.

Result: All documents which are older than 120 seconds with field value DTC or PDM will be deleted.

db.collection.createIndex( { received: 1 }, { partialFilterExpression: { topic: { $eq: "DTC" }, topic: { $eq: "PDM"} }, expireAfterSeconds: 120, name: "test_index" })

Upvotes: 0

Svetlozar
Svetlozar

Reputation: 987

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.

Upvotes: 0

Liran Mery
Liran Mery

Reputation: 181

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

Upvotes: 18

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

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

Upvotes: 5

Related Questions