猫鼬静态方法未定义

时间:2019-03-23 04:43:19

标签: javascript node.js mongoose

我正在尝试使用jwt进行身份验证,但是由于某些原因,isCorrectPassword实例中始终未定义名为user的静态方法。

如果我是console.log用户,那么我会看到has,_id等,因此数据库连接和查找有效,但静态方法无效。我不确定这是怎么回事。

// User schema
const { Schema } = require("mongoose")
const bcrypt = require("bcrypt")

const UserSchema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
})

UserSchema.statics.isCorrectPassword = function(password, callback) {
  console.log(callback)
  bcrypt.compare(password, this.password).then(function(err, same) {
    if (err) {
      callback(err)
    } else {
      callback(err, same)
    }
  })
}

module.exports = UserSchema


// User model
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const UserSchema = require("../schemas/user")

const saltRounds = 10

UserSchema.pre("save", function(next) {
  // Check if document is new or a new password has been set
  if (this.isNew || this.isModified("password")) {
    // Saving reference to this because of changing scopes
    const document = this
    bcrypt.hash(document.password, saltRounds, function(err, hashedPassword) {
      if (err) {
        next(err)
      } else {
        document.password = hashedPassword
        next()
      }
    })
  } else {
    next()
  }
})

module.exports = mongoose.model("User", UserSchema)


const jwt = require("jsonwebtoken")
const { db } = require("../db")

const secret = process.env.REACT_APP_AUTH_SECRET

function userAuth(router) {
  router.post("/authenticate", async (req, res) => {
    const { email, password } = req.body

    const Users = db.collection("users")

    Users.findOne({ email }, function(err, user) {
      if (err) {
        console.error(err)
        res.status(500).json({
          error: "Internal error please try again"
        })
      } else if (!user) {
        res.status(401).json({
          error: "Incorrect email or password"
        })
      } else {
        user.isCorrectPassword(password, function(err, same) {
          if (err) {
            res.status(500).json({
              error: "Internal error please try again"
            })
          } else if (!same) {
            res.status(401).json({
              error: "Incorrect email or password"
            })
          } else {
            // Issue token
            const payload = { email }
            const token = jwt.sign(payload, secret, {
              expiresIn: "1h"
            })
            res.cookie("token", token, { httpOnly: true }).sendStatus(200)
          }
        })
      }
    })
  })
}

module.exports = userAuth

0 个答案:

没有答案