illiteratewriter
illiteratewriter

Reputation: 4333

Unique together only if both values are present

I have a schema like this

const appSchema = new mongoose.Schema({
 email: String,
 appId: {
   type: String,
   required: true
 }
})

I have made it unique together with appUserSchema.index({ email: 1, appId: 1}, { unique: true, sparse: true });.

What should I do if I want multiple email to be empty (anonymous users)? Currently I can have only one entry with email empty because of the above constraint.

Upvotes: 0

Views: 25

Answers (1)

Ana Lava
Ana Lava

Reputation: 787

You can use partialFilterExpression option here.(mongo docs)

You can create your index as below:

appUserSchema.index({ email: 1, appId: 1}, { partialFilterExpression: { email: { $exists: true } }, unique: true});

You should remove the sparse option as it is not compatible with partial indexing. Here it only creates the compound index if email exists.

Upvotes: 1

Related Questions