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