Mongoose模式:验证唯一字段,不区分大小写 [英] Mongoose schema: Validating unique field, case insensitive

查看:483
本文介绍了Mongoose模式:验证唯一字段,不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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']
}
});

用户名字段应该是唯一的。如果该用户名已经存在于数据库中,Mongoose会抛出错误。但是,这不是不区分大小写,我需要它。



我正好在认为实现不区分大小写的唯一检查的唯一方法是写我的自己的验证规则,它将对集合执行查询?编写这样的验证检查可以创建更多的连接到集合吗?我将需要为电子邮件做类似的事情。

解决方案

如何使用:

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

达到您的目的?


I have a userSchema like so:

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']
    }
});

The username field is supposed to be unique. Mongoose will throw an error if this username already exists in the database. However, it is not case insensitive, which I need it to be.

Am I right in thinking that the only way to achieve a case insensitive unique check is to write my own validation rule, which will perform a query on the collection? Is it OK to write validation checks like this, creating more connections to the collection? I will need to do something similar for email, too.

解决方案

What about using:

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

to achieve your purpose?

这篇关于Mongoose模式:验证唯一字段,不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆