mongoose 通过.pre()存储user,password没有被加密? - CNode技术社区

mongoose 通过.pre()存储user,password没有被加密?
发布于 11 年前 作者 suntopo 5778 次浏览 最后一次编辑是 9 年前 来自 问答

额 都不知道改怎么表达了亲,刚刚接触照着慕课网教程吵得,但是为啥我存储的user不是加密后的呢? UserSchema.pre(‘save’, function(next) { var user = this; if(this.isNew) { this.meta.createAt = this.meta.updateAt = Date.now(); } else { this.meta.updateAt = Date.now(); } bcrypt.genSalt(SALT_WORK_FACTOR, 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); next() }); }); next(); });

屏幕快照 2015年06月07日 下午12.34.54.png 左边是数据库读出来的,右边是上面代码中console出来的,为什么存储的password没有被加密呢?

5 回复

左边和右边的id 都不同,你确定是同一个user?

@chita 哎呀 不小心接错图了,但是的确存在这样的问题,是我schema.pre()哪里写错了吗亲

UserSchema.pre('save', function(next) {
 var user = this
 if (this.isNew) {
 this.createAt = this.updateAt = Date.now()
 }
 else {
 this.updateAt = Date.now()
 }
 bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
 if (err) return next(err)
 bcrypt.hash(user.password, salt, function(err, hash) {
 if (err) return next(err)
 user.password = hash
 next()
 })
 })
})

我给你优化了一下

回到顶部

AltStyle によって変換されたページ (->オリジナル) /