Skip to content

Commit

Permalink
feat(connection): add listCollections() helper to connections
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jan 13, 2024
1 parent abdac8d commit 6c6fb8b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,30 @@ Connection.prototype.dropCollection = async function dropCollection(collection)
return this.db.dropCollection(collection);
};

/**
* Helper for MongoDB Node driver's `listCollections()`.
* Returns an array of collection objects.
*
* @method listCollections
* @return {Promise<Collection[]>}
* @api public
*/

Connection.prototype.listCollections = async function listCollections() {
if (arguments.length >= 2 && typeof arguments[1] === 'function') {
throw new MongooseError('Connection.prototype.dropCollection() no longer accepts a callback');
}

if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
await new Promise(resolve => {
this._queue.push({ fn: resolve });
});
}

const cursor = this.db.listCollections();
return await cursor.toArray();
};

/**
* Helper for `dropDatabase()`. Deletes the given database, including all
* collections, documents, and indexes.
Expand Down
8 changes: 8 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,14 @@ describe('connections:', function() {
const newCollectionsNames = collectionsAfterCreation.map(function(c) { return c.name; });
assert.ok(newCollectionsNames.indexOf('gh5712') !== -1);
});

it('listCollections()', async function() {
await conn.dropDatabase();
await conn.createCollection('test1176');

const collections = await conn.listCollections();
assert.deepStrictEqual(collections.map(coll => coll.name), ['test1176']);
});
});

it('should allow closing a closed connection', async function() {
Expand Down
6 changes: 6 additions & 0 deletions types/connection.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ declare module 'mongoose' {
*/
readonly id: number;

/**
* Helper for MongoDB Node driver's `listCollections()`.
* Returns an array of collection names.
*/
listCollections(collection: string): Promise<Pick<mongodb.CollectionInfo, 'name' | 'type'>[]>;

/**
* A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
* a map from model names to models. Contains all models that have been
Expand Down

0 comments on commit 6c6fb8b

Please sign in to comment.