Skip to content

Commit

Permalink
feat: Add adminCommand database method
Browse files Browse the repository at this point in the history
To run admin commands like `db.adminCommand({ dbStats: 1 })` we want to
wrap the underlying driver's admin command function.
  • Loading branch information
Garret Meier committed Oct 14, 2019
1 parent a1be4cf commit c00a988
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,14 @@ const result = await db.things.runCommand('count');
console.log(result);
```

Similarly, you can use `db.adminCommand()` to run a command on the `admin` database of the
MongoDB cluster or instance you're connected to:

```js
const result = await db.adminCommand({currentOp: 1});
console.log(result);
```

### Replication Sets

Mongoist can connect to a mongo replication set by providing a connection string with multiple hosts
Expand Down Expand Up @@ -451,6 +459,11 @@ See https://docs.mongodb.com/manual/reference/method/db.getLastErrorObj/

See https://docs.mongodb.com/manual/reference/method/db.runCommand/


#### `db.adminCommand(command)`

See https://docs.mongodb.com/manual/reference/method/db.adminCommand/

#### `db.stats()`

See https://docs.mongodb.com/manual/reference/method/db.stats/
Expand Down
12 changes: 11 additions & 1 deletion lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ const urlParser = require('mongodb/lib/url_parser.js');
const Collection = require('./collection');
const debug = require('debug')('mongoist');

function normalizeCommandOpts(opts) {
return typeof opts === 'string' ? { [opts]: 1 } : opts;
}

module.exports = class Database extends EventEmitter {
constructor(connectionString, options) {
super();
Expand Down Expand Up @@ -48,6 +52,12 @@ module.exports = class Database extends EventEmitter {
return this.listCollections().then(collections => collections.map((collection) => collection.name));
}

adminCommand(opts) {
return this
.connect()
.then(connection => connection.executeDbAdminCommand(normalizeCommandOpts(opts)));
}

runCommand(opts) {
if (typeof opts === 'string') {
opts = {
Expand All @@ -56,7 +66,7 @@ module.exports = class Database extends EventEmitter {

return this
.connect()
.then(connection => connection.command(opts));
.then(connection => connection.command(normalizeCommandOpts(opts)));
}

stats(scale) {
Expand Down
7 changes: 6 additions & 1 deletion test/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,4 +296,9 @@ describe('database', function() {
await db.close();
await db2.close();
});
});

it('should execute admin commands', async() => {
const dbStats = await db.adminCommand({ dbStats: 1 });
expect(dbStats.db).to.equal('admin');
})
});

0 comments on commit c00a988

Please sign in to comment.