'mongoDB listCollections() returns empty if nameOnly is set to true
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.
Solution 1:[1]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom Slabbaert |
