我添加了一个事件pre
挂钩updateOne
,但它的工作方式与save
事件不同......
我认为这是因为更新命令通常将匹配器作为第一个参数传递。我确实试图捕捉第二个参数,但它是一个匿名函数,我不知道如何使用。
Mongoose 文档讨论了这一点,但我不确定如何直接从 Typegoose 实际修改 Mongoose 模式。
https://mongoosejs.com/docs/middleware.html
注意:与 schema.pre('remove') 不同,Mongoose 默认在 Query#updateOne() 和 Query#deleteOne() 上注册 updateOne 和 deleteOne 中间件。这意味着 doc.updateOne() 和 Model.updateOne() 都会触发 updateOne 钩子,但这指的是查询,而不是文档。要将 updateOne 或 deleteOne 中间件注册为文档中间件,请使用 schema.pre('updateOne', { document: true, query: false })。
// this does NOT work
@pre<Question>('updateOne', function (opts) {
debug.log('updating', this)
debug.log('opts', opts)
recalcVotes(this) // incompatible type
})
// this does work
@pre<Question>('save', function () {
this.cname = this.cname || makeCname(this.text)
this.simple = this.simple || makeCname(this.text)
// mutates because we can't modify 'this = ..'
recalcVotes(this)
debug.log('cleaned', this)
})
Argument of type 'Query<Question>' is not assignable to parameter of type 'Question'.
Type 'Query<Question>' is missing the following properties from type 'Question': text, tag, _id
编辑:我刚刚更新到最新的包版本不再给出错误,但类型不同。
- "mongoose": "^5.10.15",
+ "mongoose": "^5.11.0",
并且智能感知会检测此 pre updateOne
vs save
hooks的不同类型
pre.updateOne =any
预存=this: DocumentType<Question>
npm ls mongoose
bot@1.0.0 /Users/dc/dev/ten/puzzleparty/server
└── mongoose@5.11.0
npm ls @typegoose/typegoose
bot@1.0.0 /Users/dc/dev/ten/puzzleparty/server
└── @typegoose/typegoose@7.4.2
npm -v
6.14.9
node -v
v14.5.0
npx tsc -v
Version 4.1.2