首页 > 解决方案 > 如何在猫鼬预钩子中访问请求对象

问题描述

我希望在保存文档时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
})

我该怎么做呢?

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


有一种方法可以访问模型内​​的请求对象,您可以使用此关键字

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”关键字


推荐阅读