mongoose unique validator code example
Example 1: mongoose unique field
var SimSchema = new Schema({
msisdn : { type : String , unique : true, required : true, dropDups: true },
imsi : { type : String , unique : true, required : true, dropDups: true },
status : { type : Boolean, default: true},
signal : { type : Number },
probe_name : { type: String , required : true }
});
Example 2: mongoose unique validator
npm install --save mongoose-unique-validator
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var mySchema = mongoose.Schema(/* put your schema definition here */);
mySchema.plugin(uniqueValidator);
Example 3: mongoose id validator
var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
Example 4: mongoose unique error message
emailVerificationTokenSchema.post('save', function(error, doc, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('email must be unique'));
} else {
next(error);
}
});
Example 5: express unique validator for the owner
schmea.post('save', function(error, doc, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('email must be unique'));
} else {
next(error);
}
});