【问题标题】:How can I access the request object in a mongoose pre hook如何在猫鼬预钩子中访问请求对象
【发布时间】:2021-07-22 12:04:34
【问题描述】:

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

我该怎么做呢?

【问题讨论】:

  • 代码中的任何地方都没有明确的中间件。
  • @ChrisG 我认为 OP 想要访问 mongoose pre hook 中的 req 对象。不要认为 express 中间件在这里是相关的。
  • @ChrisG 不,不是表达中间件。我的意思是猫鼬中间件(预钩子)。我编辑了标题以进行澄清
  • 你误会了。我的猜测是您需要在 express 中间件函数中运行 ProductSchema.pre() 。你怎么能在猫鼬钩子中使用req?另外,您确定这里需要 pre hook 吗?您不能在将产品直接保存到快递路线之前简单地设置产品的商家 ID 吗?
  • @ChrisG 哦,现在说得通了,谢谢。我不知道我可以在猫鼬模型之外使用 pre 钩子。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2021-06-27
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多