Home > Blockchain >  mongoDB listCollections() returns empty if nameOnly is set to true
mongoDB listCollections() returns empty if nameOnly is set to true

Time:04-12

I am using nestJS to try and get a list of collections that exist under a database. However, if I try to use the option { nameOnly: true } I get an empty array.

Below is the code I have for getting the collection names:

  @Get(':client_name/listCollections')
  async collections(@Param('client_name') client_name) {
    let arrayOfCollections;
    const db = await this.databaseService.connectToDatabase(client_name);

    try {
      arrayOfCollections = await db
        .listCollections({ nameOnly: true })
        .toArray();
    } catch (error) {
      throw error;
    }
    if (arrayOfCollections) {
      return arrayOfCollections;
    }
  }

If I remove { nameOnly: true } then I get the full list but as this puts a lock on the database and returns extra info I don't need I'd like to avoid using it if possible.

CodePudding user response:

You are just providing this option as the query of the method, all you need to do is rewrite it with an empty query:

arrayOfCollections = await db
    .listCollections({}, { nameOnly: true })
    .toArray();
  • Related