Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: listDatabases() function
  • Loading branch information
IslandRhythms committed Apr 5, 2024
commit ccfefd83664f0580a903a2f5800e98d56002a045
8 changes: 8 additions & 0 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,14 @@ Connection.prototype.listCollections = async function listCollections() {
return await cursor.toArray();
};

Connection.prototype.listDatabases = async function listDatabases() {
if (this.client) {
return this.client.db().admin().listDatabases();
} else {
throw new MongooseError('No client could be found on the given connection');
}
};

/**
* Helper for `dropDatabase()`. Deletes the given database, including all
* collections, documents, and indexes.
Expand Down
14 changes: 14 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1580,6 +1580,20 @@ describe('connections:', function() {
});
assert.ok(session);
});
it('should demonstrate the listDatabases() function (gh-9048)', async function() {
const client = await mongodb.MongoClient.connect(start.uri);
const db = mongoose.createConnection().setClient(client);
db.useDb(start.databases[1]);
const { databases } = await db.listDatabases();
assert.ok(databases);
});
it('should throw an error when no client is present (gh-9048)', async function() {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
assert.rejects(async() => {
await db.listDatabases();
}, { message: 'No client could be found on the given connection' });
});
describe('createCollections()', function() {
it('should create collections for all models on the connection with the createCollections() function (gh-13300)', async function() {
const m = new mongoose.Mongoose();
Expand Down