admin.js
12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
'use strict';
var toError = require('./utils').toError,
Define = require('./metadata'),
shallowClone = require('./utils').shallowClone,
executeOperation = require('./utils').executeOperation;
/**
* @fileOverview The **Admin** class is an internal class that allows convenient access to
* the admin functionality and commands for MongoDB.
*
* **ADMIN Cannot directly be instantiated**
* @example
* const MongoClient = require('mongodb').MongoClient;
* const test = require('assert');
* // Connection url
* const url = 'mongodb://localhost:27017';
* // Database Name
* const dbName = 'test';
*
* // Connect using MongoClient
* MongoClient.connect(url, function(err, client) {
* // Use the admin database for the operation
* const adminDb = client.db(dbName).admin();
*
* // List all the available databases
* adminDb.listDatabases(function(err, dbs) {
* test.equal(null, err);
* test.ok(dbs.databases.length > 0);
* client.close();
* });
* });
*/
/**
* Create a new Admin instance (INTERNAL TYPE, do not instantiate directly)
* @class
* @return {Admin} a collection instance.
*/
var Admin = function(db, topology, promiseLibrary) {
if (!(this instanceof Admin)) return new Admin(db, topology);
// Internal state
this.s = {
db: db,
topology: topology,
promiseLibrary: promiseLibrary
};
};
var define = (Admin.define = new Define('Admin', Admin, false));
/**
* The callback format for results
* @callback Admin~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object} result The result object if the command was executed successfully.
*/
/**
* Execute a command
* @method
* @param {object} command The command hash
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.command = function(command, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() : {};
return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [
command,
options,
callback
]);
};
define.classMethod('command', { callback: true, promise: true });
/**
* Retrieve the server information for the current
* instance of the db client
*
* @param {Object} [options] optional parameters for this operation
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.buildInfo = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
const cmd = { buildinfo: 1 };
return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [
cmd,
options,
callback
]);
};
define.classMethod('buildInfo', { callback: true, promise: true });
/**
* Retrieve the server information for the current
* instance of the db client
*
* @param {Object} [options] optional parameters for this operation
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.serverInfo = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
const cmd = { buildinfo: 1 };
return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [
cmd,
options,
callback
]);
};
define.classMethod('serverInfo', { callback: true, promise: true });
/**
* Retrieve this db's server status.
*
* @param {Object} [options] optional parameters for this operation
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.serverStatus = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.db.s.topology, serverStatus, [this, options, callback]);
};
var serverStatus = function(self, options, callback) {
self.s.db.executeDbAdminCommand({ serverStatus: 1 }, options, function(err, doc) {
if (err == null && doc.ok === 1) {
callback(null, doc);
} else {
if (err) return callback(err, false);
return callback(toError(doc), false);
}
});
};
define.classMethod('serverStatus', { callback: true, promise: true });
/**
* Ping the MongoDB server and retrieve results
*
* @param {Object} [options] optional parameters for this operation
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.ping = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
const cmd = { ping: 1 };
return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [
cmd,
options,
callback
]);
};
define.classMethod('ping', { callback: true, promise: true });
// Get write concern
var writeConcern = function(options, db) {
options = shallowClone(options);
// If options already contain write concerns return it
if (options.w || options.wtimeout || options.j || options.fsync) {
return options;
}
// Set db write concern if available
if (db.writeConcern) {
if (options.w) options.w = db.writeConcern.w;
if (options.wtimeout) options.wtimeout = db.writeConcern.wtimeout;
if (options.j) options.j = db.writeConcern.j;
if (options.fsync) options.fsync = db.writeConcern.fsync;
}
// Return modified options
return options;
};
/**
* Add a user to the database.
* @method
* @param {string} username The username.
* @param {string} password The password.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
* @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher)
* @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher)
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.addUser = function(username, password, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 2);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() : {};
options = options || {};
// Get the options
options = writeConcern(options, self.s.db);
// Set the db name to admin
options.dbName = 'admin';
return executeOperation(this.s.db.s.topology, this.s.db.addUser.bind(this.s.db), [
username,
password,
options,
callback
]);
};
define.classMethod('addUser', { callback: true, promise: true });
/**
* Remove a user from a database
* @method
* @param {string} username The username.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.removeUser = function(username, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() : {};
options = options || {};
// Get the options
options = writeConcern(options, self.s.db);
// Set the db name
options.dbName = 'admin';
return executeOperation(this.s.db.s.topology, this.s.db.removeUser.bind(this.s.db), [
username,
options,
callback
]);
};
define.classMethod('removeUser', { callback: true, promise: true });
/**
* Validate an existing collection
*
* @param {string} collectionName The name of the collection to validate.
* @param {object} [options=null] Optional settings.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback.
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.validateCollection = function(collectionName, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.db.s.topology, validateCollection, [
this,
collectionName,
options,
callback
]);
};
var validateCollection = function(self, collectionName, options, callback) {
var command = { validate: collectionName };
var keys = Object.keys(options);
// Decorate command with extra options
for (var i = 0; i < keys.length; i++) {
if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') {
command[keys[i]] = options[keys[i]];
}
}
self.s.db.command(command, options, function(err, doc) {
if (err != null) return callback(err, null);
if (doc.ok === 0) return callback(new Error('Error with validate command'), null);
if (doc.result != null && doc.result.constructor !== String)
return callback(new Error('Error with validation data'), null);
if (doc.result != null && doc.result.match(/exception|corrupt/) != null)
return callback(new Error('Error: invalid collection ' + collectionName), null);
if (doc.valid != null && !doc.valid)
return callback(new Error('Error: invalid collection ' + collectionName), null);
return callback(null, doc);
});
};
define.classMethod('validateCollection', { callback: true, promise: true });
/**
* List the available databases
*
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback.
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.listDatabases = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
var cmd = { listDatabases: 1 };
if (options.nameOnly) cmd.nameOnly = Number(cmd.nameOnly);
return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [
cmd,
options,
callback
]);
};
define.classMethod('listDatabases', { callback: true, promise: true });
/**
* Get ReplicaSet status
*
* @param {Object} [options] optional parameters for this operation
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Admin~resultCallback} [callback] The command result callback.
* @return {Promise} returns Promise if no callback passed
*/
Admin.prototype.replSetGetStatus = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.db.s.topology, replSetGetStatus, [this, options, callback]);
};
var replSetGetStatus = function(self, options, callback) {
self.s.db.executeDbAdminCommand({ replSetGetStatus: 1 }, options, function(err, doc) {
if (err == null && doc.ok === 1) return callback(null, doc);
if (err) return callback(err, false);
callback(toError(doc), false);
});
};
define.classMethod('replSetGetStatus', { callback: true, promise: true });
module.exports = Admin;