【问题标题】:Get Document ID in updateOne Post Hook in Mongoose在 Mongoose 的 updateOne Post Hook 中获取文档 ID
【发布时间】:2020-10-11 20:03:50
【问题描述】:

如何找到刚刚在 Mongoose 中使用 updateOne-post 挂钩更新的文档 id?它可能看起来像这样:

schema.post("updateOne", function (val) {
    if(val.nModified > 0) {
        /// "this" here refers to the schema, not the document...
        /// How can I get the _id field of the document that was modified?
    }
}

目前对于 Mongoose 中的 updateOne-post 挂钩,this 指的是查询,而不是正在修改的文档本身。见这里:https://mongoosejs.com/docs/middleware.html#types-of-middleware

如果在查询过程中传入id,则可以使用this.getQuery() 找到它,但这并不总是适用——我没有使用id 字段进行查询。因此,this.getQuery() 不会将我需要的数据返回给我。

有人有解决办法吗?如果可能的话,我宁愿将日志记录部分保留在我定义架构的挂钩中,以使我的代码更清晰,而不是在我运行 updateOne 函数的代码库中。

【问题讨论】:

    标签: javascript database mongodb mongoose nosql


    【解决方案1】:

    想通了!您必须使用与值一起传递的 model 以及您传入的查询重新查询文档。因此 post 挂钩如下所示:

    schema.post("updateOne", function (val) {
        if(val.nModified > 0) {
            const updatedDoc = await this.model.findOne(this.getQuery());
            console.log(updatedDoc._id)
        }
    }
    

    【讨论】:

    • 嘿,Harrison,如果您更新用​​于查询的字段,这将不起作用,例如:await Model。 updateOne( { status: 'OK' }, { $set: { status: 'KO' } });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    相关资源
    最近更新 更多