简体   繁体   English

如何使 Mongoose 区分大小写?

[英]How to make Mongoose case sensitive?

So we have an authentication system but I want to make it case insensitive for the email input.所以我们有一个身份验证系统,但我想让它对 email 输入不区分大小写。

The function looks like this: function 看起来像这样:

Auth.authenticate({ email, password })

Auth is a mongoose Model, and the users are stored in a mongo database. Auth是一个mongoose Model,用户存储在一个mongo数据库中。 This works but it is case sensitive and some users had trouble connecting.这可行,但它区分大小写,并且一些用户无法连接。

First I tried this code:首先我尝试了这段代码:

Auth.authenticate({ email: { $regex : email,$options:"i" }, password: password })

But I can't make it work, I always get this error: "Can't use password with String."但我无法让它工作,我总是得到这个错误:“不能将密码与字符串一起使用。” and I can't find on inte.net how to solve this.我在 inte.net 上找不到如何解决这个问题。

So I tried a different method, instead of using the authenticate function I will get the user and compare the password myself like this:所以我尝试了一种不同的方法,而不是使用身份验证 function 我将获取用户并自己比较密码,如下所示:

const user = await Auth.findOne({ "email" : { $regex : email,$options:"i" } })
if (user.password == password) { return true }

But the thing is, the password is encrypted with mongoosePii.但问题是,密码是用 mongoosePii 加密的。 So when I compare the two passwords I have to encrypt the password I received from the user first like this:因此,当我比较这两个密码时,我必须首先像这样加密从用户那里收到的密码:

password = await hashPassword(password)

But I get a different result... The two passwords are encrypted with the same key but for some reason they don't give the same result and I can't figure out why.但是我得到了不同的结果......这两个密码是用相同的密钥加密的,但出于某种原因,它们没有给出相同的结果,我不明白为什么。

I'm not sure which solution is better but both are fine for me if you know how to solve one of them.我不确定哪个解决方案更好,但如果您知道如何解决其中一个,那么两者都适合我。

You could do it simpler, by lowercasing every email, and having a validator on your Schema .您可以通过小写每个 email 并在您的Schema上设置一个验证器来做得更简单。 This way you don't have to write any validation about emails.这样您就不必编写任何有关电子邮件的验证。 Like so:像这样:

 npm i validator
const { isEmail } = require("validator");
const schema = Schema(
  {
    email: {
      type: String,
      required: [true, "Please enter an email"],
      unique: true,
      lowercase: true,
      validate: [isEmail, "Please enter a valid email"],
    }
  },
  
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM