skip to Main Content

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


  1. The docs page you mentioned contains this note:

    This page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.

    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>’

    Login or Signup to reply.
  2. 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 a DeleteResult, and the missing ok property will be pointed out:

    import { MongoClient } from 'mongodb'; // Version 5.2.0 as of time of writing
    
    interface Pet {
        name: string;
        kind: 'dog' | 'cat' | 'fish';
    }
    
    const client = new MongoClient('mongodb://localhost:27017');
    const pets = client.db().collection<Pet>('pets');
    
    const res = await pets.deleteMany();
    //    ^? DeleteResult
    
    if (res.deletedCount > 10) { // Okay
        // do something 
    } else {
        // do something else
    }
    
    res.ok; // Error: Property 'ok' does not exist on type 'DeleteResult'.
    //  ~~
    

    Playground Link

    Obviously, make sure your this context is properly typed as a Mongo Collection in the first place.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search