How to Validate Unique Emails with Mongoose

Feb 4, 2021

With Mongoose, you can prevent duplicates in your databases using validation. Validation is defined in the SchemaType and is a middleware. You can also create your own validation in the schema or you can use Mongooses's built in validation. To prevent duplicates, we recommend using the unique property as it tells Mongoose each document should have a unique value for a given path. It is a shorthand for creating a MongoDB unique index on, in this case, email.

If you wait for the index to be built, you can you Mongoose's promised based event, Model.init(), as shown below:

const User = mongoose.model('User', mongoose.Schema({
  email: { 
    type: String,
    required: true,
    match: /.+\@.+\..+/,
    unique: true
  }
}));
await User.create([
    { email: 'gmail@google.com' },
    { email: 'bill@microsoft.com' },
    { email: 'test@gmail.com' }
]);

await User.init();
try {
  await User.create({ email: 'gmail@google.com' });
} catch(error) {
  error.message; // 'E11000 duplicate key error...'
}

It is important to note that the unique property is not a validator.


Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!