I added a pre
hook on updateOne
events, but it works different from save
events...
I assume this is because the update command usually passes a matcher as it's first argument. I did try to catch the second argument but its an anonymous func i'm not sure how to use.
Mongoose docs talk about this, but I'm not sure how to actually modify the Mongoose schema directly from Typegoose.
https://mongoosejs.com/docs/middleware.html
Note: Unlike schema.pre('remove'), Mongoose registers updateOne and deleteOne middleware on Query#updateOne() and Query#deleteOne() by default. This means that both doc.updateOne() and Model.updateOne() trigger updateOne hooks, but this refers to a query, not a document. To register updateOne or deleteOne middleware as document middleware, use 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
EDIT: I just updated to the latest package versions No longer gives an error, but the types are different.
- "mongoose": "^5.10.15",
+ "mongoose": "^5.11.0",
and intellisense detects different types for this pre updateOne
vs save
hooks
pre.updateOne = any
pre.save = this: DocumentType<Question>
npm ls mongoose
[email protected] /Users/dc/dev/ten/puzzleparty/server
└── [email protected]
npm ls @typegoose/typegoose
[email protected] /Users/dc/dev/ten/puzzleparty/server
└── @typegoose/[email protected]
npm -v
6.14.9
node -v
v14.5.0
npx tsc -v
Version 4.1.2
I think it's complaining because you're trying to return a document, while it's just a query