Get Document ID in updateOne Post Hook in Mongoose

隐身守侯 提交于 2020-06-29 03:40:19

问题


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?
    }
}

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

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.

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.


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/62506318/get-document-id-in-updateone-post-hook-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!