这是我的mongoose模式,其中deptName是唯一的, 但我希望它也区分大小写,例如,如果xyz保存在db中,则XYZ不应保存。
var department = mongoose.Schema({
deptName: {
type: String,
unique: true,
required: true
},
deptHead: {
type: mongoose.Schema.ObjectId,
ref: 'employee'
},
active: {
type: Boolean,
default: true
}
});
答案 0 :(得分:0)
尝试通过lowercase
中的String validation进行操作。将lowercase
添加到您的架构中,如下所示
var departmentSchema = mongoose.Schema({
deptName: {
type: String,
unique: true,
required: true,
lowercase: true
}
});
当您尝试将XYZ
保存到deptName
时。验证应该失败,并且无法将此文档保存到集合中。
但是,我在Mongoose v4.4.3
中使用以下代码
var d = new Depart({
deptName: 'XYZAA'
});
d.save(function(err) {
if (err)
console.log(err);
else
console.log('Save department successfully...');
});
它可以成功保存文档并将XYZ
转换为xyz
{ "_id" : ObjectId("56c3dae36a4d4f041548f7e0"), "deptName" : "xyz", "__v" : 0 }
按照以下方式自定义验证的方法
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);
},
}
}
});
尝试将XYZ
保存到deptname
时,会出现验证错误。
{ [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' } } }