1
//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
});
});
}
});
});
当我做一个POST请求我的版本的NodeJS 8.1.2得到这个错误/注册路线:未处理的承诺拒绝在node.js中同时使用mongooseSchema.pre(“拯救”)方法
(节点:8317)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):错误:cb必须是一个函数或 null返回承诺
如果我删除猫鼬pre方法,路由工作正常。 但我想散列密码。请帮我在这个问题上。谢谢