Javascript node.bcrypt.js不更新对象中的密码
我正在使用bcrypt for Node.js加密密码。我还使用Mongoose创建MongoDB数据库和用户模型 但是,当我Javascript node.bcrypt.js不更新对象中的密码,javascript,node.js,mongodb,bcrypt,Javascript,Node.js,Mongodb,Bcrypt,我正在使用bcrypt for Node.js加密密码。我还使用Mongoose创建MongoDB数据库和用户模型 但是,当我GET数据(使用邮递员)时,明文密码不会更新为密码哈希。这是我的密码: User.js: const userSchema = new mongoose.Schema({ "email": { type: String, required: true, unique: true, trim: true }, "username": { type: String,
GET
数据(使用邮递员)时,明文密码不会更新为密码哈希。这是我的密码:
User.js:
const userSchema = new mongoose.Schema({
"email": { type: String, required: true, unique: true, trim: true },
"username": { type: String, required: true, unique: true },
"name": {
"first": String,
"last": String
},
"password": { type: String, required: true },
"created_at": { type: Date, default: Date.now },
"updated_at": { type: String }
})
userSchema.pre("save", function(next) {
var user = this
if (!user.isModified('password')) return callback()
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err)
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err)
user.password = hash
console.log(user.password)
})
})
const currentDate = new Date
user.updated_at = currentDate
next()
})
const User = mongoose.model("users", userSchema)
export default User
发布用户数据:
router.route("/users").post((req, res) => {
let json = {}
const newUser = new User({
username: req.body.username,
email: req.body.email,
name: {
first: req.body.firstName,
last: req.body.lastName
},
password: req.body.password
})
newUser.save((err) => {
if (err) {
json.error = err.message
} else {
json.id = newUser._id
}
res.json(json)
})
})
正如我上面所说的,当我获取数据时没有错误,密码仍然只是简单的明文,而不是散列。当我在函数中使用console.log(user.password)
时,它会返回哈希值
我刚刚开始学习后端的东西(我是一个前端开发人员),所以如果您有任何建议,我也会非常感激-谢谢 经典节点回调出错。在生成哈希之前调用next()回调 presave函数需要如下所示:
userSchema.pre("save", function(next) {
var user = this
if (!user.isModified('password')) return callback()
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err)
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err)
user.password = hash
const currentDate = new Date
user.updated_at = currentDate
next()
})
})
})
你不是在等待bcrypt完成。你需要在回电话时这样做。太好了,谢谢你,罗伯特!如果允许的话,我会接受你的回答。