Mongoose模式:validation唯一字段,不区分大小写

我有一个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会抛出一个错误。 但是,这不是大小写敏感的,我需要它。

我是否认为实现不区分大小写的唯一检查的唯一方法是编写自己的validation规则,它将对集合执行查询? 是否可以写这样的validation检查,创build更多的连接到集合? 我也需要为email做类似的事情。

怎么样使用:

 { type: String, lowercase: true, trim: true } 

达到你的目的?

我不知道你是否在节点上做这个。 但是你可以像这样使用一个npm: https : //github.com/blakehaswell/mongoose-unique-validator来检查集合字段上的唯一validation。 每当有新的请求到来时,其他方式都可以检查收集。 http://timstermatic.github.io/blog/2013/08/06/async-unique-validation-with-expressjs-and-mongoose/您可以参考这里的材料,并以适合您的情况的方式使用它。

最好的方法是使用已经存在的npm包作为共享下面。 https://www.npmjs.com/package/mongoose-unique-validator

为了区分大小写,您可以在同一页面中关注uniqueCaseInsensitive 。

当已经有一个可用的包时,不需要编写自己的validation逻辑(也可以关注Avinash的post )。

很简单的解决scheme

 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.' ] }, 

在这里,我使用asynchronousvalidation和检查我的模型student是否存在相同的字段。 如果你想使用显然可以使用正则expression式。

但我不会推荐这种方法,它只是不适合我的头。

而是坚持{ type: String, lowercase: true, trim: true, unique:true }方法,并将原始用户名复制到其他字段,以防万一需要。

如何使用正则expression式?

 var pattern = [ /some pattern/, "{VALUE} is not a valid user name!" ]; { type: String, match: pattern } 

如需进一步参考: http : //mongoosejs.com/docs/api.html#schematype_SchemaType-required