javascript - 如何在猫鼬预钩子中访问请求对象
问题描述
我希望在保存文档时merchantID
将其设置为登录用户。req.user
product.model.js:
const ProductSchema = new Schema({
merchantId: {
type: ObjectId,
ref: "Merchant",
required: true
},
....
})
ProductSchema.pre("save", () => {
console.log(req.user) // req object is not defined
})
我该怎么做呢?
解决方案
有一种方法可以访问模型内的请求对象,您可以使用此关键字
UserSchema.pre('save', async function(next) {
try {
if (this.isNew) {
const salt = await bcrypt.genSalt(10)
const hashedPassword = await bcrypt.hash(this.password, salt)
this.password = hashedPassword
}
next()
} catch (error) {
next(error)
}
})
这里 this.isNew 检查这是否是一个新条目,它是一个猫鼬构建的方法。您可以使用箭头函数,因为箭头函数不允许使用“this”关键字
推荐阅读
- youtube - Youtube 直播嵌入代码显示“直播离线”
- go - Golang Cronjob vs time.Ticker 用例
- node.js - Cloud9 数据库到 mLab 数据库“失败:连接到数据库服务器时出错:没有可访问的服务器”
- python - 我的 if 语句在 python 中不起作用
- javascript - 通过单选按钮的值控制 textarea 的元素属性
- python - Python Pandas - 从 extractall 返回的集合中选择最佳匹配
- python - 显示类型错误:+= 不支持的操作数类型:'int' 和 'NoneType'
- postman - 邮递员从数组中获取值并在环境变量上动态设置它
- spring-boot - Spring Boot 2.0.2 + Flowable 6.3.1 流程部署
- haskell - 如何在 Haskell 中使用列表推导?