Javascript 使用mongooschema.pre(';save';)方法时node.js中未处理的承诺拒绝
当我向/注册路由发出post请求时,我在nodejs版本8.1.2中遇到了以下错误: (节点:8317)未处理的PromisejectionWarning:未处理的承诺拒绝(拒绝id:1):错误:cb必须是函数或 回信无效 如果我删除mongoose pre方法,则该路由工作正常。Javascript 使用mongooschema.pre(';save';)方法时node.js中未处理的承诺拒绝,javascript,node.js,mongodb,mongoose,bcrypt,Javascript,Node.js,Mongodb,Mongoose,Bcrypt,当我向/注册路由发出post请求时,我在nodejs版本8.1.2中遇到了以下错误: (节点:8317)未处理的PromisejectionWarning:未处理的承诺拒绝(拒绝id:1):错误:cb必须是函数或 回信无效 如果我删除mongoose pre方法,则该路由工作正常。 但是我想散列密码。请在这个问题上帮助我。谢谢你的预保存回调使用了一个名为“done”的函数,但是你调用的是“next” 应该是: //This is the user model const mongoose = r
但是我想散列密码。请在这个问题上帮助我。谢谢你的预保存回调使用了一个名为“done”的函数,但是你调用的是“next” 应该是:
//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
});
});
}
});
});
userSchema.pre("save", function(next) {
...
}