Search code examples
javascriptnode.jsexpressexpress-validator

User.findUserByEmail is not a function


I'm using nodejs and mongoose , using express-validator to validating email duplicate,

  check("email")
    .custom(value => {
        return User.findUserByEmail(value).then(user => {
        if (user) {
            return Promise.reject('E-mail already in use');
        }
        });
    })

and when posting with duplicated email i've got error saying

{
  "errors": [
    {
      "value": "boka@gmail.com",
      "msg": "User.findUserByEmail is not a function",
      "param": "email",
      "location": "body"
    }
  ]
}

I've used reference as https://express-validator.github.io/docs/custom-validators-sanitizers.html#example-checking-if-e-mail-is-in-use

I tried to use other method such as findOne

.custom(value => {
        return User.findOne({value}).then(user => {
        if (user) {
            return Promise.reject('E-mail already in use');
        }
        });
    })

It does works but , It return response as duplicate even if email is not duplicate but writes to db

{
  "errors": [
    {
      "value": "boka1@gmail.com",
      "msg": "E-mail already in use",
      "param": "email",
      "location": "body"
    }
  ]
}

Is there something i'm missing thank you.


Solution

  • In mongoose, there is no such method on models called findUserByEmail that's why you are getting that error.

    You can use findOne instead. If you insist, I think you should define it yourself in your model.

    User.findUserByEmail = (email) => {
      return this.findOne({ email: email })
      // or return User.findOne({ email: email })
    }