mongoose-unique-validator
How to use this plugin:
1) npm install --save mongoose-unique-validator
2) in your schema follow this guide:
// declare this at the top
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
// exampleSchema = mongoose.Schema({}) etc...
exampleSchema.plugin(uniqueValidator);
// module.exports = mongoose.model(...) etc....
3) mongoose methods
When using methods like findOneAndUpdate
you will need to pass this configuration object:
{ runValidators: true, context: 'query' }
ie. User.findOneAndUpdate(
{ email: 'old-email@example.com' },
{ email: 'new-email@example.com' },
{ runValidators: true, context: 'query' },
function(err) {
// ...
}
4) additional options
case insensitive
use the uniqueCaseInsensitive option in your schema
ie. email: { type: String, index: true, unique: true, required: true, uniqueCaseInsensitive: true }
custom error messages
ie. exampleSchema.plugin(uniqueValidator, { message: 'Error, expected {PATH} to be unique.' });
Now you can add/delete the unique property to your schemas without worrying about restarting mongo, dropping databases, or creating indexes.
Caveats (from the docs):
Because we rely on async operations to verify whether a document exists in the database, it's possible for two queries to execute at the same time, both get 0 back, and then both insert into MongoDB.
Outside of automatically locking the collection or forcing a single connection, there's no real solution.
For most of our users this won't be a problem, but is an edge case to be aware of.