123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509 |
- 'use strict';
- const ChangeStream = require('./cursor/ChangeStream');
- const EventEmitter = require('events').EventEmitter;
- const Schema = require('./schema');
- const Collection = require('./driver').get().Collection;
- const STATES = require('./connectionstate');
- const MongooseError = require('./error/index');
- const PromiseProvider = require('./promise_provider');
- const ServerSelectionError = require('./error/serverSelection');
- const applyPlugins = require('./helpers/schema/applyPlugins');
- const promiseOrCallback = require('./helpers/promiseOrCallback');
- const get = require('./helpers/get');
- const immediate = require('./helpers/immediate');
- const mongodb = require('mongodb');
- const pkg = require('../package.json');
- const utils = require('./utils');
- const parseConnectionString = require('mongodb/lib/core').parseConnectionString;
- const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
- const sessionNewDocuments = require('./helpers/symbols').sessionNewDocuments;
- const noPasswordAuthMechanisms = [
- 'MONGODB-X509'
- ];
- function Connection(base) {
- this.base = base;
- this.collections = {};
- this.models = {};
- this.config = {};
- this.replica = false;
- this.options = null;
- this.otherDbs = [];
- this.relatedDbs = {};
- this.states = STATES;
- this._readyState = STATES.disconnected;
- this._closeCalled = false;
- this._hasOpened = false;
- this.plugins = [];
- if (typeof base === 'undefined' || !base.connections.length) {
- this.id = 0;
- } else {
- this.id = base.connections.length;
- }
- this._queue = [];
- }
- Connection.prototype.__proto__ = EventEmitter.prototype;
- Object.defineProperty(Connection.prototype, 'readyState', {
- get: function() {
- return this._readyState;
- },
- set: function(val) {
- if (!(val in STATES)) {
- throw new Error('Invalid connection state: ' + val);
- }
- if (this._readyState !== val) {
- this._readyState = val;
-
- for (const db of this.otherDbs) {
- db.readyState = val;
- }
- if (STATES.connected === val) {
- this._hasOpened = true;
- }
- this.emit(STATES[val]);
- }
- }
- });
- Connection.prototype.get = function(key) {
- if (this.config.hasOwnProperty(key)) {
- return this.config[key];
- }
- return get(this.options, key);
- };
- Connection.prototype.set = function(key, val) {
- if (this.config.hasOwnProperty(key)) {
- this.config[key] = val;
- return val;
- }
- this.options = this.options || {};
- this.options[key] = val;
- return val;
- };
- Connection.prototype.collections;
- Connection.prototype.name;
- Connection.prototype.models;
- Connection.prototype.id;
- Object.defineProperty(Connection.prototype, 'plugins', {
- configurable: false,
- enumerable: true,
- writable: true
- });
- Object.defineProperty(Connection.prototype, 'host', {
- configurable: true,
- enumerable: true,
- writable: true
- });
- Object.defineProperty(Connection.prototype, 'port', {
- configurable: true,
- enumerable: true,
- writable: true
- });
- Object.defineProperty(Connection.prototype, 'user', {
- configurable: true,
- enumerable: true,
- writable: true
- });
- Object.defineProperty(Connection.prototype, 'pass', {
- configurable: true,
- enumerable: true,
- writable: true
- });
- Connection.prototype.db;
- Connection.prototype.client;
- Connection.prototype.config;
- Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) {
- if (typeof options === 'function') {
- cb = options;
- options = {};
- }
- this.db.createCollection(collection, options, cb);
- });
- Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) {
- if (typeof options === 'function') {
- cb = options;
- options = null;
- }
- const session = this.client.startSession(options);
- cb(null, session);
- });
- Connection.prototype.transaction = function transaction(fn, options) {
- return this.startSession().then(session => {
- session[sessionNewDocuments] = new Map();
- return session.withTransaction(() => fn(session), options).
- then(res => {
- delete session[sessionNewDocuments];
- return res;
- }).
- catch(err => {
-
-
- for (const doc of session[sessionNewDocuments].keys()) {
- const state = session[sessionNewDocuments].get(doc);
- if (state.hasOwnProperty('isNew')) {
- doc.isNew = state.isNew;
- }
- if (state.hasOwnProperty('versionKey')) {
- doc.set(doc.schema.options.versionKey, state.versionKey);
- }
- for (const path of state.modifiedPaths) {
- doc.$__.activePaths.paths[path] = 'modify';
- doc.$__.activePaths.states.modify[path] = true;
- }
- for (const path of state.atomics.keys()) {
- const val = doc.$__getValue(path);
- if (val == null) {
- continue;
- }
- val[arrayAtomicsSymbol] = state.atomics.get(path);
- }
- }
- delete session[sessionNewDocuments];
- throw err;
- });
- });
- };
- Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) {
- this.db.dropCollection(collection, cb);
- });
- Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
-
-
-
-
- for (const name of Object.keys(this.models)) {
- delete this.models[name].$init;
- }
- this.db.dropDatabase(cb);
- });
- function _wrapConnHelper(fn) {
- return function() {
- const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null;
- const argsWithoutCb = typeof cb === 'function' ?
- Array.prototype.slice.call(arguments, 0, arguments.length - 1) :
- Array.prototype.slice.call(arguments);
- const disconnectedError = new MongooseError('Connection ' + this.id +
- ' was disconnected when calling `' + fn.name + '`');
- return promiseOrCallback(cb, cb => {
-
-
-
- immediate(() => {
- if (this.readyState === STATES.connecting && this._shouldBufferCommands()) {
- this._queue.push({ fn: fn, ctx: this, args: argsWithoutCb.concat([cb]) });
- } else if (this.readyState === STATES.disconnected && this.db == null) {
- cb(disconnectedError);
- } else {
- try {
- fn.apply(this, argsWithoutCb.concat([cb]));
- } catch (err) {
- return cb(err);
- }
- }
- });
- });
- };
- }
- Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() {
- if (this.config.bufferCommands != null) {
- return this.config.bufferCommands;
- }
- if (this.base.get('bufferCommands') != null) {
- return this.base.get('bufferCommands');
- }
- return true;
- };
- Connection.prototype.error = function(err, callback) {
- if (callback) {
- callback(err);
- return null;
- }
- if (this.listeners('error').length > 0) {
- this.emit('error', err);
- }
- return Promise.reject(err);
- };
- Connection.prototype.onOpen = function() {
- this.readyState = STATES.connected;
- for (const d of this._queue) {
- d.fn.apply(d.ctx, d.args);
- }
- this._queue = [];
-
-
- for (const i in this.collections) {
- if (utils.object.hasOwnProperty(this.collections, i)) {
- this.collections[i].onOpen();
- }
- }
- this.emit('open');
- };
- Connection.prototype.openUri = function(uri, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = null;
- }
- if (['string', 'number'].indexOf(typeof options) !== -1) {
- throw new MongooseError('Mongoose 5.x no longer supports ' +
- '`mongoose.connect(host, dbname, port)` or ' +
- '`mongoose.createConnection(host, dbname, port)`. See ' +
- 'http://mongoosejs.com/docs/connections.html for supported connection syntax');
- }
- if (typeof uri !== 'string') {
- throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
- `string, got "${typeof uri}". Make sure the first parameter to ` +
- '`mongoose.connect()` or `mongoose.createConnection()` is a string.');
- }
- if (callback != null && typeof callback !== 'function') {
- throw new MongooseError('3rd parameter to `mongoose.connect()` or ' +
- '`mongoose.createConnection()` must be a function, got "' +
- typeof callback + '"');
- }
- if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {
- if (this._connectionString !== uri) {
- throw new MongooseError('Can\'t call `openUri()` on an active connection with ' +
- 'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' +
- 'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections');
- }
- if (typeof callback === 'function') {
- this.$initialConnection = this.$initialConnection.then(
- () => callback(null, this),
- err => callback(err)
- );
- }
- return this;
- }
- this._connectionString = uri;
- this.readyState = STATES.connecting;
- this._closeCalled = false;
- const Promise = PromiseProvider.get();
- const _this = this;
- if (options) {
- options = utils.clone(options);
- const autoIndex = options.config && options.config.autoIndex != null ?
- options.config.autoIndex :
- options.autoIndex;
- if (autoIndex != null) {
- this.config.autoIndex = autoIndex !== false;
- delete options.config;
- delete options.autoIndex;
- }
- if ('autoCreate' in options) {
- this.config.autoCreate = !!options.autoCreate;
- delete options.autoCreate;
- }
- if ('useCreateIndex' in options) {
- this.config.useCreateIndex = !!options.useCreateIndex;
- delete options.useCreateIndex;
- }
- if ('useFindAndModify' in options) {
- this.config.useFindAndModify = !!options.useFindAndModify;
- delete options.useFindAndModify;
- }
-
- if (options.user || options.pass) {
- options.auth = options.auth || {};
- options.auth.user = options.user;
- options.auth.password = options.pass;
- this.user = options.user;
- this.pass = options.pass;
- }
- delete options.user;
- delete options.pass;
- if (options.bufferCommands != null) {
- if (options.bufferMaxEntries == null) {
- options.bufferMaxEntries = 0;
- }
- this.config.bufferCommands = options.bufferCommands;
- delete options.bufferCommands;
- }
- if (options.useMongoClient != null) {
- handleUseMongoClient(options);
- }
- } else {
- options = {};
- }
- this._connectionOptions = options;
- const dbName = options.dbName;
- if (dbName != null) {
- this.$dbName = dbName;
- }
- delete options.dbName;
- if (!('promiseLibrary' in options)) {
- options.promiseLibrary = PromiseProvider.get();
- }
- if (!('useNewUrlParser' in options)) {
- if ('useNewUrlParser' in this.base.options) {
- options.useNewUrlParser = this.base.options.useNewUrlParser;
- } else {
- options.useNewUrlParser = false;
- }
- }
- if (!utils.hasUserDefinedProperty(options, 'useUnifiedTopology')) {
- if (utils.hasUserDefinedProperty(this.base.options, 'useUnifiedTopology')) {
- options.useUnifiedTopology = this.base.options.useUnifiedTopology;
- } else {
- options.useUnifiedTopology = false;
- }
- }
- if (!utils.hasUserDefinedProperty(options, 'driverInfo')) {
- options.driverInfo = {
- name: 'Mongoose',
- version: pkg.version
- };
- }
- const parsePromise = new Promise((resolve, reject) => {
- parseConnectionString(uri, options, (err, parsed) => {
- if (err) {
- return reject(err);
- }
- if (dbName) {
- this.name = dbName;
- } else if (parsed.defaultDatabase) {
- this.name = parsed.defaultDatabase;
- } else {
- this.name = get(parsed, 'auth.db', null);
- }
- this.host = get(parsed, 'hosts.0.host', 'localhost');
- this.port = get(parsed, 'hosts.0.port', 27017);
- this.user = this.user || get(parsed, 'auth.username');
- this.pass = this.pass || get(parsed, 'auth.password');
- resolve();
- });
- });
- const promise = new Promise((resolve, reject) => {
- const client = new mongodb.MongoClient(uri, options);
- _this.client = client;
- client.connect((error) => {
- if (error) {
- return reject(error);
- }
- _setClient(_this, client, options, dbName);
- resolve(_this);
- });
- });
- const serverSelectionError = new ServerSelectionError();
- this.$initialConnection = Promise.all([promise, parsePromise]).
- then(res => res[0]).
- catch(err => {
- this.readyState = STATES.disconnected;
- if (err != null && err.name === 'MongoServerSelectionError') {
- err = serverSelectionError.assimilateError(err);
- }
- if (this.listeners('error').length > 0) {
- process.nextTick(() => this.emit('error', err));
- }
- throw err;
- });
- this.then = function(resolve, reject) {
- return this.$initialConnection.then(() => {
- if (typeof resolve === 'function') {
- return resolve(_this);
- }
- }, reject);
- };
- this.catch = function(reject) {
- return this.$initialConnection.catch(reject);
- };
- if (callback != null) {
- this.$initialConnection = this.$initialConnection.then(
- () => callback(null, this),
- err => callback(err)
- );
- }
- return this;
- };
- function _setClient(conn, client, options, dbName) {
- const db = dbName != null ? client.db(dbName) : client.db();
- conn.db = db;
- conn.client = client;
- conn._closeCalled = client._closeCalled;
- const _handleReconnect = () => {
-
-
-
-
- if (conn.readyState !== STATES.connected) {
- conn.readyState = STATES.connected;
- conn.emit('reconnect');
- conn.emit('reconnected');
- conn.onOpen();
- }
- };
-
- const type = get(db, 's.topology.s.description.type', '');
- if (options.useUnifiedTopology) {
- if (type === 'Single') {
- const server = Array.from(db.s.topology.s.servers.values())[0];
- server.s.topology.on('serverHeartbeatSucceeded', () => {
- _handleReconnect();
- });
- server.s.pool.on('reconnect', () => {
- _handleReconnect();
- });
- client.on('serverDescriptionChanged', ev => {
- const newDescription = ev.newDescription;
- if (newDescription.type === 'Standalone') {
- _handleReconnect();
- } else {
- conn.readyState = STATES.disconnected;
- }
- });
- } else if (type.startsWith('ReplicaSet')) {
- client.on('topologyDescriptionChanged', ev => {
-
-
- const description = ev.newDescription;
- const servers = Array.from(ev.newDescription.servers.values());
- const allServersDisconnected = description.type === 'ReplicaSetNoPrimary' &&
- servers.reduce((cur, d) => cur || d.type === 'Unknown', false);
- if (conn.readyState === STATES.connected && allServersDisconnected) {
-
- conn.readyState = STATES.disconnected;
- } else if (conn.readyState === STATES.disconnected && !allServersDisconnected) {
- _handleReconnect();
- }
- });
- client.on('close', function() {
- const type = get(db, 's.topology.s.description.type', '');
- if (type !== 'ReplicaSetWithPrimary') {
-
- conn.readyState = STATES.disconnected;
- }
- });
- }
- }
-
- db.s.topology.on('reconnectFailed', function() {
- conn.emit('reconnectFailed');
- });
- if (!options.useUnifiedTopology) {
- client.on('reconnect', function() {
- _handleReconnect();
- });
- db.s.topology.on('left', function(data) {
- conn.emit('left', data);
- });
- }
- db.s.topology.on('joined', function(data) {
- conn.emit('joined', data);
- });
- db.s.topology.on('fullsetup', function(data) {
- conn.emit('fullsetup', data);
- });
- if (get(db, 's.topology.s.coreTopology.s.pool') != null) {
- db.s.topology.s.coreTopology.s.pool.on('attemptReconnect', function() {
- conn.emit('attemptReconnect');
- });
- }
- if (!options.useUnifiedTopology) {
- client.on('close', function() {
-
- conn.readyState = STATES.disconnected;
- });
- } else if (!type.startsWith('ReplicaSet')) {
- client.on('close', function() {
-
- conn.readyState = STATES.disconnected;
- });
- }
- if (!options.useUnifiedTopology) {
- client.on('left', function() {
- if (conn.readyState === STATES.connected &&
- get(db, 's.topology.s.coreTopology.s.replicaSetState.topologyType') === 'ReplicaSetNoPrimary') {
- conn.readyState = STATES.disconnected;
- }
- });
- client.on('timeout', function() {
- conn.emit('timeout');
- });
- }
- delete conn.then;
- delete conn.catch;
- conn.onOpen();
- }
- const handleUseMongoClient = function handleUseMongoClient(options) {
- console.warn('WARNING: The `useMongoClient` option is no longer ' +
- 'necessary in mongoose 5.x, please remove it.');
- const stack = new Error().stack;
- console.warn(stack.substr(stack.indexOf('\n') + 1));
- delete options.useMongoClient;
- };
- Connection.prototype.close = function(force, callback) {
- if (typeof force === 'function') {
- callback = force;
- force = false;
- }
- this.$wasForceClosed = !!force;
- return promiseOrCallback(callback, cb => {
- this._close(force, cb);
- });
- };
- Connection.prototype._close = function(force, callback) {
- const _this = this;
- const closeCalled = this._closeCalled;
- this._closeCalled = true;
- if (this.client != null) {
- this.client._closeCalled = true;
- }
- switch (this.readyState) {
- case STATES.disconnected:
- if (closeCalled) {
- callback();
- } else {
- this.doClose(force, function(err) {
- if (err) {
- return callback(err);
- }
- _this.onClose(force);
- callback(null);
- });
- }
- break;
- case STATES.connected:
- this.readyState = STATES.disconnecting;
- this.doClose(force, function(err) {
- if (err) {
- return callback(err);
- }
- _this.onClose(force);
- callback(null);
- });
- break;
- case STATES.connecting:
- this.once('open', function() {
- _this.close(callback);
- });
- break;
- case STATES.disconnecting:
- this.once('close', function() {
- callback();
- });
- break;
- }
- return this;
- };
- Connection.prototype.onClose = function(force) {
- this.readyState = STATES.disconnected;
-
-
- for (const i in this.collections) {
- if (utils.object.hasOwnProperty(this.collections, i)) {
- this.collections[i].onClose(force);
- }
- }
- this.emit('close', force);
- };
- Connection.prototype.collection = function(name, options) {
- const defaultOptions = {
- autoIndex: this.config.autoIndex != null ? this.config.autoIndex : this.base.options.autoIndex,
- autoCreate: this.config.autoCreate != null ? this.config.autoCreate : this.base.options.autoCreate
- };
- options = Object.assign({}, defaultOptions, options ? utils.clone(options) : {});
- options.$wasForceClosed = this.$wasForceClosed;
- if (!(name in this.collections)) {
- this.collections[name] = new Collection(name, this, options);
- }
- return this.collections[name];
- };
- Connection.prototype.plugin = function(fn, opts) {
- this.plugins.push([fn, opts]);
- return this;
- };
- Connection.prototype.model = function(name, schema, collection, options) {
- if (!(this instanceof Connection)) {
- throw new MongooseError('`connection.model()` should not be run with ' +
- '`new`. If you are doing `new db.model(foo)(bar)`, use ' +
- '`db.model(foo)(bar)` instead');
- }
- let fn;
- if (typeof name === 'function') {
- fn = name;
- name = fn.name;
- }
-
- if (typeof schema === 'string') {
- collection = schema;
- schema = false;
- }
- if (utils.isObject(schema) && !schema.instanceOfSchema) {
- schema = new Schema(schema);
- }
- if (schema && !schema.instanceOfSchema) {
- throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
- 'schema or a POJO');
- }
- const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels };
- const opts = Object.assign(defaultOptions, options, { connection: this });
- if (this.models[name] && !collection && opts.overwriteModels !== true) {
-
- if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
- throw new MongooseError.OverwriteModelError(name);
- }
- return this.models[name];
- }
- let model;
- if (schema && schema.instanceOfSchema) {
- applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied');
-
- model = this.base.model(fn || name, schema, collection, opts);
-
-
- if (!this.models[name]) {
- this.models[name] = model;
- }
-
- model.init(function $modelInitNoop() {});
- return model;
- }
- if (this.models[name] && collection) {
-
- model = this.models[name];
- schema = model.prototype.schema;
- const sub = model.__subclass(this, schema, collection);
-
- return sub;
- }
-
- model = this.base.models[name];
- if (!model) {
- throw new MongooseError.MissingSchemaError(name);
- }
- if (this === model.prototype.db
- && (!collection || collection === model.collection.name)) {
-
-
-
- if (!this.models[name]) {
- this.models[name] = model;
- }
- return model;
- }
- this.models[name] = model.__subclass(this, schema, collection);
- return this.models[name];
- };
- Connection.prototype.deleteModel = function(name) {
- if (typeof name === 'string') {
- const model = this.model(name);
- if (model == null) {
- return this;
- }
- const collectionName = model.collection.name;
- delete this.models[name];
- delete this.collections[collectionName];
- delete this.base.modelSchemas[name];
- this.emit('deleteModel', model);
- } else if (name instanceof RegExp) {
- const pattern = name;
- const names = this.modelNames();
- for (const name of names) {
- if (pattern.test(name)) {
- this.deleteModel(name);
- }
- }
- } else {
- throw new Error('First parameter to `deleteModel()` must be a string ' +
- 'or regexp, got "' + name + '"');
- }
- return this;
- };
- Connection.prototype.watch = function(pipeline, options) {
- const disconnectedError = new MongooseError('Connection ' + this.id +
- ' was disconnected when calling `watch()`');
- const changeStreamThunk = cb => {
- immediate(() => {
- if (this.readyState === STATES.connecting) {
- this.once('open', function() {
- const driverChangeStream = this.db.watch(pipeline, options);
- cb(null, driverChangeStream);
- });
- } else if (this.readyState === STATES.disconnected && this.db == null) {
- cb(disconnectedError);
- } else {
- const driverChangeStream = this.db.watch(pipeline, options);
- cb(null, driverChangeStream);
- }
- });
- };
- const changeStream = new ChangeStream(changeStreamThunk, pipeline, options);
- return changeStream;
- };
- Connection.prototype.modelNames = function() {
- return Object.keys(this.models);
- };
- Connection.prototype.shouldAuthenticate = function() {
- return this.user != null &&
- (this.pass != null || this.authMechanismDoesNotRequirePassword());
- };
- Connection.prototype.authMechanismDoesNotRequirePassword = function() {
- if (this.options && this.options.auth) {
- return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0;
- }
- return true;
- };
- Connection.prototype.optionsProvideAuthenticationData = function(options) {
- return (options) &&
- (options.user) &&
- ((options.pass) || this.authMechanismDoesNotRequirePassword());
- };
- Connection.prototype.getClient = function getClient() {
- return this.client;
- };
- Connection.prototype.setClient = function setClient(client) {
- if (!(client instanceof mongodb.MongoClient)) {
- throw new MongooseError('Must call `setClient()` with an instance of MongoClient');
- }
- if (this.client != null || this.readyState !== STATES.disconnected) {
- throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.');
- }
- if (!client.isConnected()) {
- throw new MongooseError('Cannot call `setClient()` with a MongoClient that is not connected.');
- }
- this._connectionString = client.s.url;
- _setClient(this, client, { useUnifiedTopology: client.s.options.useUnifiedTopology }, client.s.options.dbName);
- return this;
- };
- Connection.STATES = STATES;
- module.exports = Connection;
|