繁体   English   中英

使用mongooseSchema.pre('save')方法时,node.js中未处理的承诺拒绝

[英]Unhandled promise rejection in node.js while using mongooseSchema.pre('save') method

//This is the user model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const userSchema = mongoose.Schema({
  email: {
    type: String,
    index: {
      unique: true
    }
  },
  password: {
    type: String
  }
});

userSchema.pre("save", function(next) {
  var user = this;
  if (!user.isModified("password")) {
    return next();
  }

  bcrypt.genSalt(saltRounds, function(err, salt) {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, salt, function(err, hashedPassword) {
      if (err) {
        return next(err)
      }
      user.password = hashedPassword;
      next();
    });
  });
});

userSchema.methods.checkPassword = function(guess, cb) {
  bcrypt.compare(guess, this.password, function(err, isMatch) {
    cb(err, isMatch);
  });
};
const User = mongoose.model('User', userSchema);
module.exports = User;


//The code below  is the /signup route
router.post('/signup', (req, res) => {
  User.findOne({
    email: req.body.email
  }, (err, user) => {
    if (err) {
      throw err;
    }

    if (user) {
      // handle case for user already exists!!
      res.json({
        success: false,
        message: 'An account with this email already exists'
      });
    } else {
      var newUser = new User({
        email: req.body.email,
        password: req.body.password
      });

      newUser.save((err) => {
        if (err) {
          return res.send(err);
        }
        let jwtData = {
          email: req.body.email
        };

        let token = jwt.sign(jwtData, jwtSecret);

        res.json({
          success: true,
          token: token
        });
      });
    }
  });
});

当我向/ signup路由发出发布请求时,在nodejs版本8.1.2中出现此错误:

(节点:8317)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):错误:cb必须为函数或为null才能返回Promise

如果我删除猫鼬的前置方法,则该路线会正常运行。 但是我想对密码进行哈希处理。在这个问题上请帮帮我。谢谢

您的预保存回调函数使用一个名为“ done”的函数,但是您正在调用“ next”。

它应该是:

userSchema.pre("save", function(next) {
    ...
}

暂无
暂无

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

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