如何调整Mongoose预存密码哈希以符合Google Javascript风格指南第5.9节?
我正在更新我的Express.js应用程序,使其完全符合Google Javascript样式指南。my Mongoose.js用户模式上的pre-save方法用于散列密码,它指的是自己使用该方法来获取要散列的密码,尽管这与Google Javascript样式指南的第5.9节冲突。如何调整预保存方法以避免使用此方法,并符合第5.9节的要求 代码如何调整Mongoose预存密码哈希以符合Google Javascript风格指南第5.9节?,javascript,mongoose,this,Javascript,Mongoose,This,我正在更新我的Express.js应用程序,使其完全符合Google Javascript样式指南。my Mongoose.js用户模式上的pre-save方法用于散列密码,它指的是自己使用该方法来获取要散列的密码,尽管这与Google Javascript样式指南的第5.9节冲突。如何调整预保存方法以避免使用此方法,并符合第5.9节的要求 代码 UserSchema.pre('save', (next) => { bcrypt.hash(this.password, 10,
UserSchema.pre('save', (next) => {
bcrypt.hash(this.password, 10, (err, hash) => {
if (err) {
return next(err);
}
this.password = hash;
next();
});
});
谷歌Javascript风格指南要求
5.9本
仅在类构造函数和方法中使用,或在类构造函数和方法中定义的箭头函数中使用。此函数的任何其他用途都必须在立即封闭函数的JSDoc中声明一个显式@this
千万不要用它来引用全局对象、eval的上下文、事件的目标,或者不必要地调用()ed或apply()ed函数
Nathaniel,arrow函数与普通函数不一样。您应该始终使用公共函数声明mongoose实例和静态方法、virtuals、getter/setter和中间件 考虑以下示例:
#!/usr/bin/env node
'use strict'
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
const Schema = mongoose.Schema
const schema = new Schema({
name: String
})
schema.pre('save', (next) => {
console.log('arrow:', this)
next()
})
schema.pre('save', function (next) {
console.log('common:', this)
next()
})
const Test = mongoose.model('test', schema)
const test = new Test({ name: 'billy' })
test.save().then(() => {
return mongoose.connection.close()
})
产出:
gitter: ./nsuchy.js
arrow: {}
common: { _id: 5ac734c8b41a6b2591c30a9c, name: 'billy' }
gitter: