问题
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