[英]Unable to store bcrypt hashed password from JSON into mongodb using mongoose
我无法使用猫鼬将bcrypt哈希密码从JSON存储到mongodb中。 我认为setPassword模式方法的实现存在错误。 我已将“ bcrypt”替换为“ crypto”实现,并且运行良好。 哈希字符串存储在数据库中。 但是用“ bcrypt”无法做到
我的model.js实现
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
// User Schema
const userSchema = new Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
}
});
userSchema.methods.setPassword = function(password) {
const saltRounds = 10;
bcrypt.hash(password, saltRounds, function(err, hash) {
this.password = hash;
});
};
mongoose.model('User', userSchema);
我的路由器控制器实现
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');
const register = (req, res) => {
const newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.username = req.body.username;
newUser.setPassword(req.body.password);
newUser.save((err) => {
// Validations error
if (err) {
res.status(400).json(err);
return;
}
res.status(200).json({
success: true,
message: 'Registration Successful'
});
});
};
this
指向bcrypt.hash
而不是userSchema对象。
userSchema.methods.setPassword = function(password) {
const saltRounds = 10;
var that = this;
bcrypt.hash(password, saltRounds, function(err, hash) {
that.password = hash;
});
};
更新:使用回调或promise
userSchema.methods.setPassword = function(password, cb) {
const saltRounds = 10;
var that = this;
bcrypt.hash(password, saltRounds, function(err, hash) {
that.password = hash;
cb();
});
};
newUser.setPassword(req.body.password, function(){
//Rest of code
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.