1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054 |
- 'use strict';
- const EventEmitter = require('events').EventEmitter;
- const inherits = require('util').inherits;
- const getSingleProperty = require('./utils').getSingleProperty;
- const CommandCursor = require('./command_cursor');
- const handleCallback = require('./utils').handleCallback;
- const filterOptions = require('./utils').filterOptions;
- const toError = require('./utils').toError;
- const ReadPreference = require('./core').ReadPreference;
- const MongoError = require('./core').MongoError;
- const ObjectID = require('./core').ObjectID;
- const Logger = require('./core').Logger;
- const Collection = require('./collection');
- const conditionallyMergeWriteConcern = require('./utils').conditionallyMergeWriteConcern;
- const executeLegacyOperation = require('./utils').executeLegacyOperation;
- const ChangeStream = require('./change_stream');
- const deprecate = require('util').deprecate;
- const deprecateOptions = require('./utils').deprecateOptions;
- const MongoDBNamespace = require('./utils').MongoDBNamespace;
- const CONSTANTS = require('./constants');
- const WriteConcern = require('./write_concern');
- const ReadConcern = require('./read_concern');
- const AggregationCursor = require('./aggregation_cursor');
- const createListener = require('./operations/db_ops').createListener;
- const ensureIndex = require('./operations/db_ops').ensureIndex;
- const evaluate = require('./operations/db_ops').evaluate;
- const profilingInfo = require('./operations/db_ops').profilingInfo;
- const validateDatabaseName = require('./operations/db_ops').validateDatabaseName;
- const AggregateOperation = require('./operations/aggregate');
- const AddUserOperation = require('./operations/add_user');
- const CollectionsOperation = require('./operations/collections');
- const CommandOperation = require('./operations/command');
- const RunCommandOperation = require('./operations/run_command');
- const CreateCollectionOperation = require('./operations/create_collection');
- const CreateIndexesOperation = require('./operations/create_indexes');
- const DropCollectionOperation = require('./operations/drop').DropCollectionOperation;
- const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation;
- const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command');
- const IndexInformationOperation = require('./operations/index_information');
- const ListCollectionsOperation = require('./operations/list_collections');
- const ProfilingLevelOperation = require('./operations/profiling_level');
- const RemoveUserOperation = require('./operations/remove_user');
- const RenameOperation = require('./operations/rename');
- const SetProfilingLevelOperation = require('./operations/set_profiling_level');
- const executeOperation = require('./operations/execute_operation');
- const legalOptionNames = [
- 'w',
- 'wtimeout',
- 'fsync',
- 'j',
- 'writeConcern',
- 'readPreference',
- 'readPreferenceTags',
- 'native_parser',
- 'forceServerObjectId',
- 'pkFactory',
- 'serializeFunctions',
- 'raw',
- 'bufferMaxEntries',
- 'authSource',
- 'ignoreUndefined',
- 'promoteLongs',
- 'promiseLibrary',
- 'readConcern',
- 'retryMiliSeconds',
- 'numberOfRetries',
- 'parentDb',
- 'noListener',
- 'loggerLevel',
- 'logger',
- 'promoteBuffers',
- 'promoteLongs',
- 'promoteValues',
- 'compression',
- 'retryWrites'
- ];
- function Db(databaseName, topology, options) {
- options = options || {};
- if (!(this instanceof Db)) return new Db(databaseName, topology, options);
- EventEmitter.call(this);
-
- const promiseLibrary = options.promiseLibrary || Promise;
-
- options = filterOptions(options, legalOptionNames);
-
- options.promiseLibrary = promiseLibrary;
-
- this.s = {
-
- dbCache: {},
-
- children: [],
-
- topology: topology,
-
- options: options,
-
- logger: Logger('Db', options),
-
- bson: topology ? topology.bson : null,
-
- readPreference: ReadPreference.fromOptions(options),
-
- bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1,
-
- parentDb: options.parentDb || null,
-
- pkFactory: options.pkFactory || ObjectID,
-
- nativeParser: options.nativeParser || options.native_parser,
-
- promiseLibrary: promiseLibrary,
-
- noListener: typeof options.noListener === 'boolean' ? options.noListener : false,
-
- readConcern: ReadConcern.fromOptions(options),
- writeConcern: WriteConcern.fromOptions(options),
-
- namespace: new MongoDBNamespace(databaseName)
- };
-
- validateDatabaseName(databaseName);
-
- getSingleProperty(this, 'serverConfig', this.s.topology);
- getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries);
- getSingleProperty(this, 'databaseName', this.s.namespace.db);
-
- if (options.parentDb) return;
- if (this.s.noListener) return;
-
- topology.on('error', createListener(this, 'error', this));
- topology.on('timeout', createListener(this, 'timeout', this));
- topology.on('close', createListener(this, 'close', this));
- topology.on('parseError', createListener(this, 'parseError', this));
- topology.once('open', createListener(this, 'open', this));
- topology.once('fullsetup', createListener(this, 'fullsetup', this));
- topology.once('all', createListener(this, 'all', this));
- topology.on('reconnect', createListener(this, 'reconnect', this));
- }
- inherits(Db, EventEmitter);
- Db.prototype.on = deprecate(function() {
- return Db.super_.prototype.on.apply(this, arguments);
- }, 'Listening to events on the Db class has been deprecated and will be removed in the next major version.');
- Db.prototype.once = deprecate(function() {
- return Db.super_.prototype.once.apply(this, arguments);
- }, 'Listening to events on the Db class has been deprecated and will be removed in the next major version.');
- Object.defineProperty(Db.prototype, 'topology', {
- enumerable: true,
- get: function() {
- return this.s.topology;
- }
- });
- Object.defineProperty(Db.prototype, 'options', {
- enumerable: true,
- get: function() {
- return this.s.options;
- }
- });
- Object.defineProperty(Db.prototype, 'slaveOk', {
- enumerable: true,
- get: function() {
- if (
- this.s.options.readPreference != null &&
- (this.s.options.readPreference !== 'primary' ||
- this.s.options.readPreference.mode !== 'primary')
- ) {
- return true;
- }
- return false;
- }
- });
- Object.defineProperty(Db.prototype, 'readConcern', {
- enumerable: true,
- get: function() {
- return this.s.readConcern;
- }
- });
- Object.defineProperty(Db.prototype, 'readPreference', {
- enumerable: true,
- get: function() {
- if (this.s.readPreference == null) {
-
- return ReadPreference.primary;
- }
- return this.s.readPreference;
- }
- });
- Object.defineProperty(Db.prototype, 'writeConcern', {
- enumerable: true,
- get: function() {
- return this.s.writeConcern;
- }
- });
- Object.defineProperty(Db.prototype, 'namespace', {
- enumerable: true,
- get: function() {
- return this.s.namespace.toString();
- }
- });
- Db.prototype.command = function(command, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = Object.assign({}, options);
- const commandOperation = new RunCommandOperation(this, command, options);
- return executeOperation(this.s.topology, commandOperation, callback);
- };
- Db.prototype.aggregate = function(pipeline, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
-
-
- if (options == null && callback == null) {
- options = {};
- }
- const cursor = new AggregationCursor(
- this.s.topology,
- new AggregateOperation(this, pipeline, options),
- options
- );
-
- if (typeof callback === 'function') {
- callback(null, cursor);
- return;
- }
- return cursor;
- };
- Db.prototype.admin = function() {
- const Admin = require('./admin');
- return new Admin(this, this.s.topology, this.s.promiseLibrary);
- };
- const COLLECTION_OPTION_KEYS = [
- 'pkFactory',
- 'readPreference',
- 'serializeFunctions',
- 'strict',
- 'readConcern',
- 'ignoreUndefined',
- 'promoteValues',
- 'promoteBuffers',
- 'promoteLongs'
- ];
- Db.prototype.collection = function(name, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- options = Object.assign({}, options);
-
- options.promiseLibrary = this.s.promiseLibrary;
-
- options.readConcern = options.readConcern
- ? new ReadConcern(options.readConcern.level)
- : this.readConcern;
-
- if (this.s.options.ignoreUndefined) {
- options.ignoreUndefined = this.s.options.ignoreUndefined;
- }
- for (const collectionOptionKey of COLLECTION_OPTION_KEYS) {
- if (!(collectionOptionKey in options) && this.s.options[collectionOptionKey] !== undefined) {
- options[collectionOptionKey] = this.s.options[collectionOptionKey];
- }
- }
-
- options = conditionallyMergeWriteConcern(options, this.s.options);
-
- if (options == null || !options.strict) {
- try {
- const collection = new Collection(
- this,
- this.s.topology,
- this.databaseName,
- name,
- this.s.pkFactory,
- options
- );
- if (callback) callback(null, collection);
- return collection;
- } catch (err) {
- if (err instanceof MongoError && callback) return callback(err);
- throw err;
- }
- }
-
- if (typeof callback !== 'function') {
- throw toError(`A callback is required in strict mode. While getting collection ${name}`);
- }
-
- if (this.serverConfig && this.serverConfig.isDestroyed()) {
- return callback(new MongoError('topology was destroyed'));
- }
- const listCollectionOptions = Object.assign({}, options, { nameOnly: true });
-
- this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => {
- if (err != null) return handleCallback(callback, err, null);
- if (collections.length === 0)
- return handleCallback(
- callback,
- toError(`Collection ${name} does not exist. Currently in strict mode.`),
- null
- );
- try {
- return handleCallback(
- callback,
- null,
- new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options)
- );
- } catch (err) {
- return handleCallback(callback, err, null);
- }
- });
- };
- Db.prototype.createCollection = deprecateOptions(
- {
- name: 'Db.createCollection',
- deprecatedOptions: ['autoIndexId', 'strict', 'w', 'wtimeout', 'j'],
- optionsIndex: 1
- },
- function(name, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;
- options.readConcern = options.readConcern
- ? new ReadConcern(options.readConcern.level)
- : this.readConcern;
- const createCollectionOperation = new CreateCollectionOperation(this, name, options);
- return executeOperation(this.s.topology, createCollectionOperation, callback);
- }
- );
- Db.prototype.stats = function(options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
-
- const commandObject = { dbStats: true };
-
- if (options['scale'] != null) commandObject['scale'] = options['scale'];
-
- if (options.readPreference == null && this.s.readPreference) {
- options.readPreference = this.s.readPreference;
- }
- const statsOperation = new CommandOperation(this, options, null, commandObject);
-
- return executeOperation(this.s.topology, statsOperation, callback);
- };
- Db.prototype.listCollections = function(filter, options) {
- filter = filter || {};
- options = options || {};
- return new CommandCursor(
- this.s.topology,
- new ListCollectionsOperation(this, filter, options),
- options
- );
- };
- Db.prototype.eval = deprecate(function(code, parameters, options, callback) {
- const args = Array.prototype.slice.call(arguments, 1);
- callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
- parameters = args.length ? args.shift() : parameters;
- options = args.length ? args.shift() || {} : {};
- return executeLegacyOperation(this.s.topology, evaluate, [
- this,
- code,
- parameters,
- options,
- callback
- ]);
- }, 'Db.eval is deprecated as of MongoDB version 3.2');
- Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
-
- options.new_collection = true;
- const renameOperation = new RenameOperation(
- this.collection(fromCollection),
- toCollection,
- options
- );
- return executeOperation(this.s.topology, renameOperation, callback);
- };
- Db.prototype.dropCollection = function(name, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const dropCollectionOperation = new DropCollectionOperation(this, name, options);
- return executeOperation(this.s.topology, dropCollectionOperation, callback);
- };
- Db.prototype.dropDatabase = function(options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const dropDatabaseOperation = new DropDatabaseOperation(this, options);
- return executeOperation(this.s.topology, dropDatabaseOperation, callback);
- };
- Db.prototype.collections = function(options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const collectionsOperation = new CollectionsOperation(this, options);
- return executeOperation(this.s.topology, collectionsOperation, callback);
- };
- Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- options.readPreference = ReadPreference.resolve(this, options);
- const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation(
- this,
- selector,
- options
- );
- return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback);
- };
- Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options ? Object.assign({}, options) : {};
- const createIndexesOperation = new CreateIndexesOperation(this, name, fieldOrSpec, options);
- return executeOperation(this.s.topology, createIndexesOperation, callback);
- };
- Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- return executeLegacyOperation(this.s.topology, ensureIndex, [
- this,
- name,
- fieldOrSpec,
- options,
- callback
- ]);
- }, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0');
- Db.prototype.addChild = function(db) {
- if (this.s.parentDb) return this.s.parentDb.addChild(db);
- this.s.children.push(db);
- };
- Db.prototype.addUser = function(username, password, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
-
- if (typeof username === 'string' && password != null && typeof password === 'object') {
- options = password;
- password = null;
- }
- const addUserOperation = new AddUserOperation(this, username, password, options);
- return executeOperation(this.s.topology, addUserOperation, callback);
- };
- Db.prototype.removeUser = function(username, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const removeUserOperation = new RemoveUserOperation(this, username, options);
- return executeOperation(this.s.topology, removeUserOperation, callback);
- };
- Db.prototype.setProfilingLevel = function(level, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options);
- return executeOperation(this.s.topology, setProfilingLevelOperation, callback);
- };
- Db.prototype.profilingInfo = deprecate(function(options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]);
- }, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.');
- Db.prototype.profilingLevel = function(options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const profilingLevelOperation = new ProfilingLevelOperation(this, options);
- return executeOperation(this.s.topology, profilingLevelOperation, callback);
- };
- Db.prototype.indexInformation = function(name, options, callback) {
- if (typeof options === 'function') (callback = options), (options = {});
- options = options || {};
- const indexInformationOperation = new IndexInformationOperation(this, name, options);
- return executeOperation(this.s.topology, indexInformationOperation, callback);
- };
- Db.prototype.unref = function() {
- this.s.topology.unref();
- };
- Db.prototype.watch = function(pipeline, options) {
- pipeline = pipeline || [];
- options = options || {};
-
- if (!Array.isArray(pipeline)) {
- options = pipeline;
- pipeline = [];
- }
- return new ChangeStream(this, pipeline, options);
- };
- Db.prototype.getLogger = function() {
- return this.s.logger;
- };
- Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
- Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
- Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
- Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
- Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
- Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
- module.exports = Db;
|