Is there a way to conditionally set 'unique' in Mongoose Schema?

Viewed 357

I came across a problem while implementing user deletion functionality. A

Suppose I have a model:

const UserSchema = new mongoose.Schema(
        {
            email: { type: String, required: true, unique: true },
            name: { type: String, required: true },
            password: { type: String, required: true },
            deleted: {type: Date, default: null}
        },
        { timestamps: true }
    );

This clearly states that the field email has to be unique. However, I would like to set it unique only in the set filtered for deleted != null.

In other words, I would like to filter out the deleted users' records before checking if it is unique or not.

Are there any best practices regarding this?

Or should I just create a field called del-email and null the email field to avoid over-complication and preserve the data?

1 Answers

You can try,

Partial index with unique constraint:

  • The partial unique index, you can specify the filter expression condition, if it matches then the unique index will take the role,
UserSchema.index(
   { email: 1 },
   { unique: true, partialFilterExpression: { deleted: { $eq: null } } }
);

Note: As noted in the query coverage documentation for partial indexes:

To use the partial index, a query must contain the filter expression (or a modified filter expression that specifies a subset of the filter expression) as part of its query condition.

User.find({ email: "something@mail.com", deleted: null });
Related