我有一个 userSchema
像这样:
var userSchema = new Schema({
name: {
type: String
, required: true
, validate: [validators.notEmpty, 'Name is empty']
}
, username: {
type: String
, required: true
, unique: true
, validate: [validators.notEmpty, 'Username is empty']
}
});
该 username
字段应该是唯一的。如果此用户名已存在于数据库中,则Mongoose将抛出错误。但是,它不是不区分大小写的,我需要它。
我是否正确地认为实现不区分大小写的唯一检查的唯一方法是编写我自己的验证规则,该规则将对集合执行查询?可以编写这样的验证检查,创建更多与集合的连接吗?我需要做类似的事情 email
也是。
怎么样使用:
{ type: String, lowercase: true, trim: true }
实现你的目的?
怎么样使用:
{ type: String, lowercase: true, trim: true }
实现你的目的?
很简单的解决方案
username : {
trim:true,
//lowercase:true,
type:String,
required:[true, '{PATH} is required.'],
match : [
new RegExp('^[a-z0-9_.-]+$', 'i'),
'{PATH} \'{VALUE}\' is not valid. Use only letters, numbers, underscore or dot.'
],
minlength:5,
maxlength:30,
//unique:true
validate : [
function(un, cb){
console.log(v);
student.findOne({username:/^un$/i}, function(err, doc){
if(err) return console.log(err);
if(!_.isEmpty(doc)) return cb(false);
return cb(true);
});
},
'Username already exists.'
]
},
在这里,我使用异步验证并检查我的模型 student
如果存在相同的字段。如果你愿意,使用显然可以使用正则表达式。
但我不推荐这种方法,它只是不适合我的想法。
相反坚持 { type: String, lowercase: true, trim: true, unique:true }
接近并将原始用户名复制到其他字段,以备不时之需。
使用正则表达式怎么样?
var pattern = [ /some pattern/, "{VALUE} is not a valid user name!" ];
{ type: String, match: pattern }
供进一步参考: http://mongoosejs.com/docs/api.html#schematype_SchemaType-required