在update中获取文档ID [英] Get Document ID in updateOne Post Hook in Mongoose

查看:24
本文介绍了在update中获取文档ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I find the document id that was just updated using the updateOne-post hook in Mongoose? It might look something like this:

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中间件

Currently for the updateOne-post hook in Mongoose, this refers to the query, not to the document itself being modified. See here: https://mongoosejs.com/docs/middleware.html#types-of-middleware

使用 this.getQuery()可以找到在查询过程中传入的 id ,但这并不总是适用的.不使用 id 字段进行查询.因此, this.getQuery()不会向我返回我需要的数据.

It's possible to find the id if it was passed in during the query, using this.getQuery() but this isn't always applicable——I'm not querying using the id field. Thus, the this.getQuery() doesn't return to me the data I'm needing.

有人可以解决吗?我宁愿将日志记录部分保留在我定义架构的钩子中,以尽可能使我的代码更整洁,而不是在运行 updateOne 函数的代码库中.

Does anyone have the solution? I'd rather keep the logging portion in the hooks, where I define my schema, to make my code cleaner, if possible, rather than within my codebase where I'm running the updateOne function.

推荐答案

想通了!您必须使用随值传递的 model 和传递的查询来重新查询文档.因此,后钩看起来像这样:

Figured it out! You have to re-query for the document, using the model that gets passed along with the value, and the query that you passed in. So the post hook looks like this:

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

这篇关于在update中获取文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆