mongoose中间件使用时的疑惑
发布于 6 年前 作者 Choicelin 2764 次浏览 来自 问答

在用到pre(‘findOneAndUpdate’,function(next) {…})时,从回调的this里面获取到的字段是undefined,如果schema定义了字段meta,然后在执行findOneAndUpdate操作后,pre操作中回调获取this.meta是undefined,目前对mongoose还不太熟,不知从何分析

2 回复

自问自答一波,引用

Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn’t necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated.

本来就是更新操作,目前解决方案是直接在update对象里将meta更新了

回到顶部