gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:12:15 26 4
gpt4 key购买 nike

我正在更新我的 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();
});
});

Google Javascript 样式指南要求

5.9 this

Only use this in class constructors and methods, or in arrow functions defined within class constructors and methods. Any other uses of this must have an explicit @this declared in the immediately-enclosing function’s JSDoc.

Never use this to refer to the global object, the context of an eval, the target of an event, or unnecessarily call()ed or apply()ed functions.

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

最佳答案

Nathaniel,箭头函数不会将 this 视为普通函数。您应该始终声明 mongoose 实例和静态方法、虚拟方法、getters/setters 以及具有常用功能的中间件。

考虑以下示例:

#!/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:

check the 4th question down on the FAQ here

关于javascript - 如何调整 Mongoose 预保存密码哈希以符合 Google Javascript 风格指南第 5.9 节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49682710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com