In my app I do some work on Mongo collection method’s responses and would like to make things easier by typing them, but can’t seem to find how to do it.
One of the cases in point is deleteMany
. According to the docs, the response should be
{ "acknowledged" : true, "deletedCount" : X }
Is there not a type somewhere for this? Or do I need to manually type it on my end?
This has unfortunately caused a problem when upgrading form an older version of mongo to v6 since the response no longer contained ok
. It would be nice to have a type from Mongo that would’ve shown a TS error whenever the property no longer existed.
The code looks something like this:
const res = await this.deleteMany(query) // res is currently an any type
if (res.deletedCount > 10) {
// do something
} else {
// do something else
}
The issue with that is that res
is typed as any
. And I would like to know if indeed I need to construct my own type or I can import it from somewhere in case changes are made in the later version.
Thanks
2
Answers
The docs page you mentioned contains this note:
The correct documentation for that function in the node.js driver is:
https://mongodb.github.io/node-mongodb-native/5.2/classes/Collection.html#deleteMany
Which tells us the return type is ‘Promise<DeleteResult>’
If you have the proper
mongodb
Node.js driver version (5.2.0 as of time of writing), you should have built-in TypeScript definitions.With this, your
res
variable should be properly typed as aDeleteResult
, and the missingok
property will be pointed out:Playground Link
Obviously, make sure your
this
context is properly typed as a Mongo Collection in the first place.