How to use mongoose unique


The term unique is a mongoose default boolean SchemaType. In a mongoose model, a SchemaType says what type a given path should have and what values are valid for that path. It doesn’t actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.

The unique option tells Mongoose that each document must have a unique value for a given path. It is a boolean SchemaType. By default, it remains false but when you mention it, it returns true and checks if the particular value is unique or not.

Suppose you have an application where different users can register with their email. But you want each user to have only one account. So how can you implement it? The simplest way to do it is to set unique: true for the email field. Here is the implementation below :

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true // `email` must be unique
  }
});
const User = mongoose.model('User', userSchema);

Now, If you try to create two users with the same email, you’ll get a duplicate key error. Because mongoose does not allow you to create a new user with the same email if it has already existed in the database before.

// Throws `MongoError: E11000 duplicate key error collection...`
await User.create([
  { email: 'abc@google.com' },
  { email: 'abc@google.com' }
]);

const doc = new User({ email: 'abc@google.com' });
// Throws `MongoError: E11000 duplicate key error collection...`
await doc.save();

It will work for the updates as well. Updates can also throw a duplicate key error. For example, if you create a user with a unique email address and then update their email address to a non-unique value, you’ll get the same error.

await User.create({ email: 'test2@google.com' });

// Throws `MongoError: E11000 duplicate key error collection...`
await User.updateOne({ email: 'test2@google.com' }, { email: 'test@google.com' });

This is all about mongoose unique and you can learn how to use it and know the errors also.


Share on social media

//