Home > Net >  How to make Mongoose case sensitive?
How to make Mongoose case sensitive?

Time:02-19

So we have an authentication system but I want to make it case insensitive for the email input.

The function looks like this:

Auth.authenticate({ email, password })

Auth is a mongoose Model, and the users are stored in a mongo database. 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 internet how to solve this.

So I tried a different method, instead of using the authenticate function I will get the user and compare the password myself like this:

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. 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.

CodePudding user response:

You could do it simpler, by lowercasing every email, and having a validator on your 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"],
    }
  },
  
);
  • Related