0

Is there a built-in way to say that a field should be unique if it is not null. For example, I want users to have a unique phone number, but this is not a required field. So it can be null, and hence it breaks the unique constraint if another user is added without a phone number.

This is almost the same question: mongoDB/mongoose: unique if not null but with newer versions of both mongoose and mongodb, I guess there should be a better way to achieve this.

Community
  • 1
  • 1
Vivek V Dwivedi
  • 2,510
  • 2
  • 28
  • 39
  • you can use Partial Index with Unique Constraint refer:https://docs.mongodb.com/v3.2/core/index-partial/#partial-index-with-unique-constraints – Simran Nov 23 '16 at 10:05

1 Answers1

5

If you dont like to combine sparse and unique indexes like in answer you provided

db.users.ensureIndex({ phone: 1 }, { unique: true, sparse: true });

You can use partial index, which is not implemented in mongoose, but available as a native operator.

db.users.createIndex(
   { phone: 1 },
   { partialFilterExpression: { phone: { $exists: true } } }
)
Community
  • 1
  • 1
styopdev
  • 2,604
  • 4
  • 34
  • 55