UNPKG

26.7 kBJavaScriptView Raw
1'use strict';
2
3/*!
4 * Module dependencies.
5 */
6
7const EventEmitter = require('events').EventEmitter;
8const Schema = require('./schema');
9const Collection = require('./driver').get().Collection;
10const STATES = require('./connectionstate');
11const MongooseError = require('./error');
12const PromiseProvider = require('./promise_provider');
13const get = require('lodash.get');
14const mongodb = require('mongodb');
15const utils = require('./utils');
16
17const parseConnectionString = require('mongodb-core').parseConnectionString;
18
19/*!
20 * A list of authentication mechanisms that don't require a password for authentication.
21 * This is used by the authMechanismDoesNotRequirePassword method.
22 *
23 * @api private
24 */
25const noPasswordAuthMechanisms = [
26 'MONGODB-X509'
27];
28
29/**
30 * Connection constructor
31 *
32 * For practical reasons, a Connection equals a Db.
33 *
34 * @param {Mongoose} base a mongoose instance
35 * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
36 * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection.
37 * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
38 * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.
39 * @event `disconnecting`: Emitted when `connection.close()` was executed.
40 * @event `disconnected`: Emitted after getting disconnected from the db.
41 * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.
42 * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection.
43 * @event `error`: Emitted when an error occurs on this connection.
44 * @event `fullsetup`: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
45 * @event `all`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
46 * @api public
47 */
48
49function Connection(base) {
50 this.base = base;
51 this.collections = {};
52 this.models = {};
53 this.config = {autoIndex: true};
54 this.replica = false;
55 this.options = null;
56 this.otherDbs = []; // FIXME: To be replaced with relatedDbs
57 this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection
58 this.states = STATES;
59 this._readyState = STATES.disconnected;
60 this._closeCalled = false;
61 this._hasOpened = false;
62
63 this.$internalEmitter = new EventEmitter();
64 this.$internalEmitter.setMaxListeners(0);
65}
66
67/*!
68 * Inherit from EventEmitter
69 */
70
71Connection.prototype.__proto__ = EventEmitter.prototype;
72
73/**
74 * Connection ready state
75 *
76 * - 0 = disconnected
77 * - 1 = connected
78 * - 2 = connecting
79 * - 3 = disconnecting
80 *
81 * Each state change emits its associated event name.
82 *
83 * ####Example
84 *
85 * conn.on('connected', callback);
86 * conn.on('disconnected', callback);
87 *
88 * @property readyState
89 * @memberOf Connection
90 * @instance
91 * @api public
92 */
93
94Object.defineProperty(Connection.prototype, 'readyState', {
95 get: function() {
96 return this._readyState;
97 },
98 set: function(val) {
99 if (!(val in STATES)) {
100 throw new Error('Invalid connection state: ' + val);
101 }
102
103 if (this._readyState !== val) {
104 this._readyState = val;
105 // [legacy] loop over the otherDbs on this connection and change their state
106 for (let i = 0; i < this.otherDbs.length; i++) {
107 this.otherDbs[i].readyState = val;
108 }
109
110 // loop over relatedDbs on this connection and change their state
111 for (const k in this.relatedDbs) {
112 this.relatedDbs[k].readyState = val;
113 }
114
115 if (STATES.connected === val) {
116 this._hasOpened = true;
117 }
118
119 this.emit(STATES[val]);
120 }
121 }
122});
123
124/**
125 * A hash of the collections associated with this connection
126 *
127 * @property collections
128 * @memberOf Connection
129 * @instance
130 * @api public
131 */
132
133Connection.prototype.collections;
134
135/**
136 * The name of the database this connection points to.
137 *
138 * ####Example
139 *
140 * mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb"
141 *
142 * @property name
143 * @memberOf Connection
144 * @instance
145 * @api public
146 */
147
148Connection.prototype.name;
149
150/**
151 * The host name portion of the URI. If multiple hosts, such as a replica set,
152 * this will contain the first host name in the URI
153 *
154 * ####Example
155 *
156 * mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost"
157 *
158 * @property host
159 * @memberOf Connection
160 * @instance
161 * @api public
162 */
163
164Object.defineProperty(Connection.prototype, 'host', {
165 configurable: true,
166 enumerable: true,
167 writable: true
168});
169
170/**
171 * The port portion of the URI. If multiple hosts, such as a replica set,
172 * this will contain the port from the first host name in the URI.
173 *
174 * ####Example
175 *
176 * mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017
177 *
178 * @property port
179 * @memberOf Connection
180 * @instance
181 * @api public
182 */
183
184Object.defineProperty(Connection.prototype, 'port', {
185 configurable: true,
186 enumerable: true,
187 writable: true
188});
189
190/**
191 * The username specified in the URI
192 *
193 * ####Example
194 *
195 * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val"
196 *
197 * @property user
198 * @memberOf Connection
199 * @instance
200 * @api public
201 */
202
203Object.defineProperty(Connection.prototype, 'user', {
204 configurable: true,
205 enumerable: true,
206 writable: true
207});
208
209/**
210 * The password specified in the URI
211 *
212 * ####Example
213 *
214 * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw"
215 *
216 * @property pass
217 * @memberOf Connection
218 * @instance
219 * @api public
220 */
221
222Object.defineProperty(Connection.prototype, 'pass', {
223 configurable: true,
224 enumerable: true,
225 writable: true
226});
227
228/**
229 * The mongodb.Db instance, set when the connection is opened
230 *
231 * @property db
232 * @memberOf Connection
233 * @instance
234 * @api public
235 */
236
237Connection.prototype.db;
238
239/**
240 * A hash of the global options that are associated with this connection
241 *
242 * @property config
243 * @memberOf Connection
244 * @instance
245 * @api public
246 */
247
248Connection.prototype.config;
249
250/**
251 * Helper for `createCollection()`. Will explicitly create the given collection
252 * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
253 * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
254 *
255 * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection)
256 *
257 * @method createCollection
258 * @param {string} collection The collection to create
259 * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection)
260 * @param {Function} [callback]
261 * @return {Promise}
262 * @api public
263 */
264
265Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) {
266 if (typeof options === 'function') {
267 cb = options;
268 options = {};
269 }
270 this.db.createCollection(collection, options, cb);
271});
272
273/**
274 * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
275 * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
276 * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
277 *
278 * ####Example:
279 *
280 * const session = await conn.startSession();
281 * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
282 * await doc.remove();
283 * // `doc` will always be null, even if reading from a replica set
284 * // secondary. Without causal consistency, it is possible to
285 * // get a doc back from the below query if the query reads from a
286 * // secondary that is experiencing replication lag.
287 * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
288 *
289 *
290 * @method startSession
291 * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
292 * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
293 * @param {Function} [callback]
294 * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
295 * @api public
296 */
297
298Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) {
299 if (typeof options === 'function') {
300 cb = options;
301 options = null;
302 }
303 const session = this.client.startSession(options);
304 cb(null, session);
305});
306
307/**
308 * Helper for `dropCollection()`. Will delete the given collection, including
309 * all documents and indexes.
310 *
311 * @method dropCollection
312 * @param {string} collection The collection to delete
313 * @param {Function} [callback]
314 * @return {Promise}
315 * @api public
316 */
317
318Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) {
319 this.db.dropCollection(collection, cb);
320});
321
322/**
323 * Helper for `dropDatabase()`. Deletes the given database, including all
324 * collections, documents, and indexes.
325 *
326 * @method dropDatabase
327 * @param {Function} [callback]
328 * @return {Promise}
329 * @api public
330 */
331
332Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
333 this.$internalEmitter.emit('dropDatabase');
334 this.db.dropDatabase(cb);
335});
336
337/*!
338 * ignore
339 */
340
341function _wrapConnHelper(fn) {
342 return function() {
343 const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null;
344 const argsWithoutCb = typeof cb === 'function' ?
345 Array.prototype.slice.call(arguments, 0, arguments.length - 1) :
346 Array.prototype.slice.call(arguments);
347 return utils.promiseOrCallback(cb, cb => {
348 if (this.readyState !== STATES.connected) {
349 this.once('open', function() {
350 fn.apply(this, argsWithoutCb.concat([cb]));
351 });
352 } else {
353 fn.apply(this, argsWithoutCb.concat([cb]));
354 }
355 });
356 };
357}
358
359/**
360 * error
361 *
362 * Graceful error handling, passes error to callback
363 * if available, else emits error on the connection.
364 *
365 * @param {Error} err
366 * @param {Function} callback optional
367 * @api private
368 */
369
370Connection.prototype.error = function(err, callback) {
371 if (callback) {
372 callback(err);
373 return null;
374 }
375 if (this.listeners('error').length > 0) {
376 this.emit('error', err);
377 }
378 return Promise.reject(err);
379};
380
381/**
382 * Called when the connection is opened
383 *
384 * @api private
385 */
386
387Connection.prototype.onOpen = function() {
388 this.readyState = STATES.connected;
389
390 // avoid having the collection subscribe to our event emitter
391 // to prevent 0.3 warning
392 for (const i in this.collections) {
393 if (utils.object.hasOwnProperty(this.collections, i)) {
394 this.collections[i].onOpen();
395 }
396 }
397
398 this.emit('open');
399};
400
401/**
402 * Opens the connection with a URI using `MongoClient.connect()`.
403 *
404 * @param {String} uri The URI to connect with.
405 * @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect
406 * @param {Function} [callback]
407 * @returns {Connection} this
408 * @api private
409 */
410
411Connection.prototype.openUri = function(uri, options, callback) {
412 this.readyState = STATES.connecting;
413 this._closeCalled = false;
414
415 if (typeof options === 'function') {
416 callback = options;
417 options = null;
418 }
419
420 if (['string', 'number'].indexOf(typeof options) !== -1) {
421 throw new MongooseError('Mongoose 5.x no longer supports ' +
422 '`mongoose.connect(host, dbname, port)` or ' +
423 '`mongoose.createConnection(host, dbname, port)`. See ' +
424 'http://mongoosejs.com/docs/connections.html for supported connection syntax');
425 }
426
427 if (typeof uri !== 'string') {
428 throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
429 `string, got "${typeof uri}". Make sure the first parameter to ` +
430 '`mongoose.connect()` or `mongoose.createConnection()` is a string.');
431 }
432
433 const Promise = PromiseProvider.get();
434 const _this = this;
435
436 if (options) {
437 options = utils.clone(options);
438 const autoIndex = options.config && options.config.autoIndex != null ?
439 options.config.autoIndex :
440 options.autoIndex;
441 if (autoIndex != null) {
442 this.config.autoIndex = autoIndex !== false;
443 delete options.config;
444 delete options.autoIndex;
445 }
446
447 if ('autoCreate' in options) {
448 this.config.autoCreate = !!options.autoCreate;
449 delete options.autoCreate;
450 }
451 if ('useCreateIndex' in options) {
452 this.config.useCreateIndex = !!options.useCreateIndex;
453 delete options.useCreateIndex;
454 }
455
456 // Backwards compat
457 if (options.user || options.pass) {
458 options.auth = options.auth || {};
459 options.auth.user = options.user;
460 options.auth.password = options.pass;
461
462 this.user = options.user;
463 this.pass = options.pass;
464 }
465 delete options.user;
466 delete options.pass;
467
468 if (options.bufferCommands != null) {
469 options.bufferMaxEntries = 0;
470 this.config.bufferCommands = options.bufferCommands;
471 delete options.bufferCommands;
472 }
473
474 if (options.useMongoClient != null) {
475 handleUseMongoClient(options);
476 }
477 } else {
478 options = {};
479 }
480
481 this._connectionOptions = options;
482 const dbName = options.dbName;
483 if (dbName != null) {
484 this.$dbName = dbName;
485 }
486 delete options.dbName;
487
488 if (!('promiseLibrary' in options)) {
489 options.promiseLibrary = PromiseProvider.get();
490 }
491 if (!('useNewUrlParser' in options)) {
492 if ('useNewUrlParser' in this.base.options) {
493 options.useNewUrlParser = this.base.options.useNewUrlParser;
494 } else {
495 options.useNewUrlParser = false;
496 }
497 }
498
499 const parsePromise = new Promise((resolve, reject) => {
500 parseConnectionString(uri, options, (err, parsed) => {
501 if (err) {
502 return reject(err);
503 }
504 this.name = dbName != null ? dbName : get(parsed, 'auth.db', null);
505 this.host = get(parsed, 'hosts.0.host') || 'localhost';
506 this.port = get(parsed, 'hosts.0.port') || 27017;
507 this.user = this.user || get(parsed, 'auth.username');
508 this.pass = this.pass || get(parsed, 'auth.password');
509 resolve();
510 });
511 });
512
513 const promise = new Promise((resolve, reject) => {
514 const client = new mongodb.MongoClient(uri, options);
515 _this.client = client;
516 client.connect(function(error) {
517 if (error) {
518 _this.readyState = STATES.disconnected;
519 return reject(error);
520 }
521
522 const db = dbName != null ? client.db(dbName) : client.db();
523 _this.db = db;
524
525 // Backwards compat for mongoose 4.x
526 db.on('reconnect', function() {
527 _this.readyState = STATES.connected;
528 _this.emit('reconnect');
529 _this.emit('reconnected');
530 });
531 db.s.topology.on('reconnectFailed', function() {
532 _this.emit('reconnectFailed');
533 });
534 db.s.topology.on('left', function(data) {
535 _this.emit('left', data);
536 });
537 db.s.topology.on('joined', function(data) {
538 _this.emit('joined', data);
539 });
540 db.s.topology.on('fullsetup', function(data) {
541 _this.emit('fullsetup', data);
542 });
543 db.on('close', function() {
544 // Implicitly emits 'disconnected'
545 _this.readyState = STATES.disconnected;
546 });
547 db.on('timeout', function() {
548 _this.emit('timeout');
549 });
550
551 delete _this.then;
552 delete _this.catch;
553 _this.readyState = STATES.connected;
554
555 for (const i in _this.collections) {
556 if (utils.object.hasOwnProperty(_this.collections, i)) {
557 _this.collections[i].onOpen();
558 }
559 }
560
561 resolve(_this);
562 _this.emit('open');
563 });
564 });
565
566 this.$initialConnection = Promise.all([promise, parsePromise]).
567 then(res => res[0]).
568 catch(err => {
569 if (this.listeners('error').length > 0) {
570 process.nextTick(() => this.emit('error', err));
571 return;
572 }
573 throw err;
574 });
575 this.then = function(resolve, reject) {
576 return this.$initialConnection.then(resolve, reject);
577 };
578 this.catch = function(reject) {
579 return this.$initialConnection.catch(reject);
580 };
581
582 if (callback != null) {
583 this.$initialConnection.then(
584 () => callback(null, this),
585 err => callback(err)
586 );
587 }
588
589 return this;
590};
591
592/*!
593 * ignore
594 */
595
596const handleUseMongoClient = function handleUseMongoClient(options) {
597 console.warn('WARNING: The `useMongoClient` option is no longer ' +
598 'necessary in mongoose 5.x, please remove it.');
599 const stack = new Error().stack;
600 console.warn(stack.substr(stack.indexOf('\n') + 1));
601 delete options.useMongoClient;
602};
603
604/**
605 * Closes the connection
606 *
607 * @param {Boolean} [force] optional
608 * @param {Function} [callback] optional
609 * @return {Connection} self
610 * @api public
611 */
612
613Connection.prototype.close = function(force, callback) {
614 if (typeof force === 'function') {
615 callback = force;
616 force = false;
617 }
618
619 this.$wasForceClosed = !!force;
620
621 return utils.promiseOrCallback(callback, cb => {
622 this._close(force, cb);
623 });
624};
625
626/**
627 * Handles closing the connection
628 *
629 * @param {Boolean} force
630 * @param {Function} callback
631 * @api private
632 */
633Connection.prototype._close = function(force, callback) {
634 const _this = this;
635 this._closeCalled = true;
636
637 switch (this.readyState) {
638 case 0: // disconnected
639 callback();
640 break;
641
642 case 1: // connected
643 this.readyState = STATES.disconnecting;
644 this.doClose(force, function(err) {
645 if (err) {
646 return callback(err);
647 }
648 _this.onClose(force);
649 callback(null);
650 });
651
652 break;
653 case 2: // connecting
654 this.once('open', function() {
655 _this.close(callback);
656 });
657 break;
658
659 case 3: // disconnecting
660 this.once('close', function() {
661 callback();
662 });
663 break;
664 }
665
666 return this;
667};
668
669/**
670 * Called when the connection closes
671 *
672 * @api private
673 */
674
675Connection.prototype.onClose = function(force) {
676 this.readyState = STATES.disconnected;
677
678 // avoid having the collection subscribe to our event emitter
679 // to prevent 0.3 warning
680 for (const i in this.collections) {
681 if (utils.object.hasOwnProperty(this.collections, i)) {
682 this.collections[i].onClose(force);
683 }
684 }
685
686 this.emit('close', force);
687};
688
689/**
690 * Retrieves a collection, creating it if not cached.
691 *
692 * Not typically needed by applications. Just talk to your collection through your model.
693 *
694 * @param {String} name of the collection
695 * @param {Object} [options] optional collection options
696 * @return {Collection} collection instance
697 * @api public
698 */
699
700Connection.prototype.collection = function(name, options) {
701 options = options ? utils.clone(options) : {};
702 options.$wasForceClosed = this.$wasForceClosed;
703 if (!(name in this.collections)) {
704 this.collections[name] = new Collection(name, this, options);
705 }
706 return this.collections[name];
707};
708
709/**
710 * Defines or retrieves a model.
711 *
712 * var mongoose = require('mongoose');
713 * var db = mongoose.createConnection(..);
714 * db.model('Venue', new Schema(..));
715 * var Ticket = db.model('Ticket', new Schema(..));
716 * var Venue = db.model('Venue');
717 *
718 * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
719 *
720 * ####Example:
721 *
722 * var schema = new Schema({ name: String }, { collection: 'actor' });
723 *
724 * // or
725 *
726 * schema.set('collection', 'actor');
727 *
728 * // or
729 *
730 * var collectionName = 'actor'
731 * var M = conn.model('Actor', schema, collectionName)
732 *
733 * @param {String|Function} name the model name or class extending Model
734 * @param {Schema} [schema] a schema. necessary when defining a model
735 * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
736 * @see Mongoose#model #index_Mongoose-model
737 * @return {Model} The compiled model
738 * @api public
739 */
740
741Connection.prototype.model = function(name, schema, collection) {
742 if (!(this instanceof Connection)) {
743 throw new MongooseError('`connection.model()` should not be run with ' +
744 '`new`. If you are doing `new db.model(foo)(bar)`, use ' +
745 '`db.model(foo)(bar)` instead');
746 }
747
748 let fn;
749 if (typeof name === 'function') {
750 fn = name;
751 name = fn.name;
752 }
753
754 // collection name discovery
755 if (typeof schema === 'string') {
756 collection = schema;
757 schema = false;
758 }
759
760 if (utils.isObject(schema) && !schema.instanceOfSchema) {
761 schema = new Schema(schema);
762 }
763 if (schema && !schema.instanceOfSchema) {
764 throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
765 'schema or a POJO');
766 }
767
768 if (this.models[name] && !collection) {
769 // model exists but we are not subclassing with custom collection
770 if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
771 throw new MongooseError.OverwriteModelError(name);
772 }
773 return this.models[name];
774 }
775
776 const opts = {cache: false, connection: this};
777 let model;
778
779 if (schema && schema.instanceOfSchema) {
780 // compile a model
781 model = this.base.model(fn || name, schema, collection, opts);
782
783 // only the first model with this name is cached to allow
784 // for one-offs with custom collection names etc.
785 if (!this.models[name]) {
786 this.models[name] = model;
787 }
788
789 // Errors handled internally, so safe to ignore error
790 model.init(function $modelInitNoop() {});
791
792 return model;
793 }
794
795 if (this.models[name] && collection) {
796 // subclassing current model with alternate collection
797 model = this.models[name];
798 schema = model.prototype.schema;
799 const sub = model.__subclass(this, schema, collection);
800 // do not cache the sub model
801 return sub;
802 }
803
804 // lookup model in mongoose module
805 model = this.base.models[name];
806
807 if (!model) {
808 throw new MongooseError.MissingSchemaError(name);
809 }
810
811 if (this === model.prototype.db
812 && (!collection || collection === model.collection.name)) {
813 // model already uses this connection.
814
815 // only the first model with this name is cached to allow
816 // for one-offs with custom collection names etc.
817 if (!this.models[name]) {
818 this.models[name] = model;
819 }
820
821 return model;
822 }
823 this.models[name] = model.__subclass(this, schema, collection);
824 return this.models[name];
825};
826
827/**
828 * Removes the model named `name` from this connection, if it exists. You can
829 * use this function to clean up any models you created in your tests to
830 * prevent OverwriteModelErrors.
831 *
832 * ####Example:
833 *
834 * conn.model('User', new Schema({ name: String }));
835 * console.log(conn.model('User')); // Model object
836 * conn.deleteModel('User');
837 * console.log(conn.model('User')); // undefined
838 *
839 * // Usually useful in a Mocha `afterEach()` hook
840 * afterEach(function() {
841 * conn.deleteModel(/.+/); // Delete every model
842 * });
843 *
844 * @api public
845 * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
846 * @return {Connection} this
847 */
848
849Connection.prototype.deleteModel = function(name) {
850 if (typeof name === 'string') {
851 const model = this.model(name);
852 if (model == null) {
853 return this;
854 }
855 delete this.models[name];
856 delete this.collections[model.collection.name];
857 delete this.base.modelSchemas[name];
858 } else if (name instanceof RegExp) {
859 const pattern = name;
860 const names = this.modelNames();
861 for (const name of names) {
862 if (pattern.test(name)) {
863 this.deleteModel(name);
864 }
865 }
866 } else {
867 throw new Error('First parameter to `deleteModel()` must be a string ' +
868 'or regexp, got "' + name + '"');
869 }
870
871 return this;
872};
873
874/**
875 * Returns an array of model names created on this connection.
876 * @api public
877 * @return {Array}
878 */
879
880Connection.prototype.modelNames = function() {
881 return Object.keys(this.models);
882};
883
884/**
885 * @brief Returns if the connection requires authentication after it is opened. Generally if a
886 * username and password are both provided than authentication is needed, but in some cases a
887 * password is not required.
888 * @api private
889 * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false.
890 */
891Connection.prototype.shouldAuthenticate = function() {
892 return this.user != null &&
893 (this.pass != null || this.authMechanismDoesNotRequirePassword());
894};
895
896/**
897 * @brief Returns a boolean value that specifies if the current authentication mechanism needs a
898 * password to authenticate according to the auth objects passed into the openUri methods.
899 * @api private
900 * @return {Boolean} true if the authentication mechanism specified in the options object requires
901 * a password, otherwise false.
902 */
903Connection.prototype.authMechanismDoesNotRequirePassword = function() {
904 if (this.options && this.options.auth) {
905 return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0;
906 }
907 return true;
908};
909
910/**
911 * @brief Returns a boolean value that specifies if the provided objects object provides enough
912 * data to authenticate with. Generally this is true if the username and password are both specified
913 * but in some authentication methods, a password is not required for authentication so only a username
914 * is required.
915 * @param {Object} [options] the options object passed into the openUri methods.
916 * @api private
917 * @return {Boolean} true if the provided options object provides enough data to authenticate with,
918 * otherwise false.
919 */
920Connection.prototype.optionsProvideAuthenticationData = function(options) {
921 return (options) &&
922 (options.user) &&
923 ((options.pass) || this.authMechanismDoesNotRequirePassword());
924};
925
926/**
927 * Switches to a different database using the same connection pool.
928 *
929 * Returns a new connection object, with the new db.
930 *
931 * @method useDb
932 * @memberOf Connection
933 * @param {String} name The database name
934 * @return {Connection} New Connection Object
935 * @api public
936 */
937
938/*!
939 * Module exports.
940 */
941
942Connection.STATES = STATES;
943module.exports = Connection;