如何调整猫鼬预保存密码哈希以符合 Google Javascript 风格指南第 5.9 节?



我正在更新我的Express.js应用程序,使其完全符合Google Javascript风格指南。我的 Mongoose.js 用户模式哈希密码的预保存方法是指自己使用它来获取要哈希的密码,尽管这与 Google Javascript 风格指南的第 5.9 节冲突。如何调整预保存方法以避免使用它并符合第 5.9 节?

法典

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 的上下文、事件的目标,或者不必要的 call()ed 或 apply()ed 函数。

https://google.github.io/styleguide/jsguide.html#features-this

Nathaniel,箭头函数不把this当作常用函数。您应该始终声明猫鼬实例和静态方法、虚拟方法、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:

在此处查看常见问题解答中的第 4 个问题

最新更新