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

标签 javascript node.js mongodb mongoose bcrypt

//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 中收到此错误:

( Node :8317)UnhandledPromiseRejectionWarning:未处理的 promise 拒绝(拒绝 ID:1):错误:cb 必须是函数或 null 返回 Promise

如果我删除 mongoose pre 方法,该路线工作正常。 但我想对密码进行哈希处理。请帮助我解决这个问题。谢谢

最佳答案

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

应该是:

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

关于javascript - 使用 mongooseSchema.pre ('save' ) 方法时,node.js 中未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44952136/

相关文章:

Mongodb 得到错误信息 "MongoError: Path collision at activity"

python - pymongo update_one 语法错误

javascript - 在 nvd3 图表中更改 xAxis 的日期格式

javascript - 是否可以以编程方式检测数据 url 的大小限制?

javascript - 最新的 Google Angular CDN 不工作

node.js - Nodejs+ Mongoose : find and update

node.js - Docker-compose 失败并出现错误 "No command specified"

node.js - 有没有办法告诉是什么让 node.js 程序保持活力?

mongodb - 旧驱动程序版本与新 mongodb 服务器的兼容性

javascript - 如何阻止 JS 驱动的整页滚动跳转到开始/结束