mongoose unique

Mongoose Unique

If you are working with MongoDB and using Mongoose as your ODM (object data modeling), you may come across the need to enforce unique constraints on fields in your schema. This is where the unique property comes into play.

Let me share my experience with this. I was building a blog platform using Node.js, Express.js, MongoDB, and Mongoose. I wanted to make sure that usernames were unique for each user in my database. To achieve this, I added a unique: true property to the username field in my user schema:


const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true // this ensures that the username is unique
  },
  email: {
    type: String,
    required: true,
    unique: true // this ensures that the email is unique
  },
  passwordHash: {
    type: String,
    required: true
  }
});

This tells Mongoose to create a unique index on the username and email fields. If you try to insert a document with a duplicate value for either of these fields, Mongoose will throw a MongoError with an error code of 11000.

Unique Indexes in MongoDB

It's worth noting that the unique property in Mongoose is just a shorthand for creating a unique index in MongoDB. You can actually create a unique index manually using the createIndex method on your model:


const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  passwordHash: {
    type: String,
    required: true
  }
});

userSchema.index({ username: 1 }, { unique: true });
userSchema.index({ email: 1 }, { unique: true });

const UserModel = mongoose.model('User', userSchema);

// create the indexes
UserModel.createIndexes();

This code creates two unique indexes, one on the username field and one on the email field. It then calls the createIndexes method on the model to actually create the indexes in the database.

Conclusion

The unique property in Mongoose is a convenient way to enforce unique constraints on fields in your schema. Under the hood, it creates a unique index in MongoDB. If you need more control over the index creation process, you can create indexes manually using the createIndex method on your model.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe