Try to do it through lowercase
in the String validation. Add lowercase
to your schema as below
var departmentSchema = mongoose.Schema({
deptName: {
type: String,
unique: true,
required: true,
lowercase: true
}
});
When you try to save XYZ
to deptName
. The validation should be failed and cannot save this document into collection.
However, I test it in the Mongoose v4.4.3
with following codes
var d = new Depart({
deptName: 'XYZAA'
});
d.save(function(err) {
if (err)
console.log(err);
else
console.log('Save department successfully...');
});
And it could save the document successfully and convert XYZ
to xyz
{ "_id" : ObjectId("56c3dae36a4d4f041548f7e0"), "deptName" : "xyz", "__v" : 0 }
Anther way to custom the validation as following
var departmentSchema = mongoose.Schema({
deptName: {
type: String,
unique: true,
required: true,
validate: {
validator: function(v) {
if (v && v.length)
var re = /^[a-z]$/i;
return re.test(v);
},
}
}
});
When try to save XYZ
to deptname
, validation error will come up.
{ [ValidationError: Depart validation failed]
message: 'Depart validation failed',
name: 'ValidationError',
errors:
{ deptName:
{ [ValidatorError: Validator failed for path `deptName` with value `XYZ`]
properties: [Object],
message: 'Validator failed for path `deptName` with value `XYZ`',
name: 'ValidatorError',
kind: 'user defined',
path: 'deptName',
value: 'XYZ' } } }