How to make a collection store unique entries if the entry not null with Mongoose?

Sometimes, we want to make a collection store unique entries if the entry not null with Mongoose.

In this article, we’ll look at how to make a collection store unique entries if the entry not null with Mongoose.

How to make a collection store unique entries if the entry not null with Mongoose?

To make a collection store unique entries if the entry not null with Mongoose, we can specify a unique constraint when we define the schema.

For instance, we write

const UsersSchema = new Schema({
  name: {
    type: String,
    trim: true,
    index: true,
    required: true
  },
  email: {
    type: String,
    trim: true,
    index: {
      unique: true,
      partialFilterExpression: {
        email: {
          $type: "string"
        }
      }
    }
  }
});

to define UserSchema with the email field required to be unique for each entry.

The constraint is set by setting index.unique to true.

Conclusion

To make a collection store unique entries if the entry not null with Mongoose, we can specify a unique constraint when we define the schema.