UNPKG

27.1 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('./helpers/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 if ('useFindAndModify' in options) {
457 this.config.useFindAndModify = !!options.useFindAndModify;
458 delete options.useFindAndModify;
459 }
460
461 // Backwards compat
462 if (options.user || options.pass) {
463 options.auth = options.auth || {};
464 options.auth.user = options.user;
465 options.auth.password = options.pass;
466
467 this.user = options.user;
468 this.pass = options.pass;
469 }
470 delete options.user;
471 delete options.pass;
472
473 if (options.bufferCommands != null) {
474 options.bufferMaxEntries = 0;
475 this.config.bufferCommands = options.bufferCommands;
476 delete options.bufferCommands;
477 }
478
479 if (options.useMongoClient != null) {
480 handleUseMongoClient(options);
481 }
482 } else {
483 options = {};
484 }
485
486 this._connectionOptions = options;
487 const dbName = options.dbName;
488 if (dbName != null) {
489 this.$dbName = dbName;
490 }
491 delete options.dbName;
492
493 if (!('promiseLibrary' in options)) {
494 options.promiseLibrary = PromiseProvider.get();
495 }
496 if (!('useNewUrlParser' in options)) {
497 if ('useNewUrlParser' in this.base.options) {
498 options.useNewUrlParser = this.base.options.useNewUrlParser;
499 } else {
500 options.useNewUrlParser = false;
501 }
502 }
503
504 const parsePromise = new Promise((resolve, reject) => {
505 parseConnectionString(uri, options, (err, parsed) => {
506 if (err) {
507 return reject(err);
508 }
509 this.name = dbName != null ? dbName : get(parsed, 'auth.db', null);
510 this.host = get(parsed, 'hosts.0.host', 'localhost');
511 this.port = get(parsed, 'hosts.0.port', 27017);
512 this.user = this.user || get(parsed, 'auth.username');
513 this.pass = this.pass || get(parsed, 'auth.password');
514 resolve();
515 });
516 });
517
518 const promise = new Promise((resolve, reject) => {
519 const client = new mongodb.MongoClient(uri, options);
520 _this.client = client;
521 client.connect(function(error) {
522 if (error) {
523 _this.readyState = STATES.disconnected;
524 return reject(error);
525 }
526
527 const db = dbName != null ? client.db(dbName) : client.db();
528 _this.db = db;
529
530 // Backwards compat for mongoose 4.x
531 db.on('reconnect', function() {
532 _this.readyState = STATES.connected;
533 _this.emit('reconnect');
534 _this.emit('reconnected');
535 });
536 db.s.topology.on('reconnectFailed', function() {
537 _this.emit('reconnectFailed');
538 });
539 db.s.topology.on('left', function(data) {
540 _this.emit('left', data);
541 });
542 db.s.topology.on('joined', function(data) {
543 _this.emit('joined', data);
544 });
545 db.s.topology.on('fullsetup', function(data) {
546 _this.emit('fullsetup', data);
547 });
548 db.on('close', function() {
549 // Implicitly emits 'disconnected'
550 _this.readyState = STATES.disconnected;
551 });
552 client.on('left', function() {
553 if (_this.readyState === STATES.connected &&
554 get(db, 's.topology.s.coreTopology.s.replicaSetState.topologyType') === 'ReplicaSetNoPrimary') {
555 _this.readyState = STATES.disconnected;
556 }
557 });
558 db.on('timeout', function() {
559 _this.emit('timeout');
560 });
561
562 delete _this.then;
563 delete _this.catch;
564 _this.readyState = STATES.connected;
565
566 for (const i in _this.collections) {
567 if (utils.object.hasOwnProperty(_this.collections, i)) {
568 _this.collections[i].onOpen();
569 }
570 }
571
572 resolve(_this);
573 _this.emit('open');
574 });
575 });
576
577 this.$initialConnection = Promise.all([promise, parsePromise]).
578 then(res => res[0]).
579 catch(err => {
580 if (this.listeners('error').length > 0) {
581 process.nextTick(() => this.emit('error', err));
582 return;
583 }
584 throw err;
585 });
586 this.then = function(resolve, reject) {
587 return this.$initialConnection.then(resolve, reject);
588 };
589 this.catch = function(reject) {
590 return this.$initialConnection.catch(reject);
591 };
592
593 if (callback != null) {
594 this.$initialConnection = this.$initialConnection.then(
595 () => callback(null, this),
596 err => callback(err)
597 );
598 }
599
600 return this;
601};
602
603/*!
604 * ignore
605 */
606
607const handleUseMongoClient = function handleUseMongoClient(options) {
608 console.warn('WARNING: The `useMongoClient` option is no longer ' +
609 'necessary in mongoose 5.x, please remove it.');
610 const stack = new Error().stack;
611 console.warn(stack.substr(stack.indexOf('\n') + 1));
612 delete options.useMongoClient;
613};
614
615/**
616 * Closes the connection
617 *
618 * @param {Boolean} [force] optional
619 * @param {Function} [callback] optional
620 * @return {Connection} self
621 * @api public
622 */
623
624Connection.prototype.close = function(force, callback) {
625 if (typeof force === 'function') {
626 callback = force;
627 force = false;
628 }
629
630 this.$wasForceClosed = !!force;
631
632 return utils.promiseOrCallback(callback, cb => {
633 this._close(force, cb);
634 });
635};
636
637/**
638 * Handles closing the connection
639 *
640 * @param {Boolean} force
641 * @param {Function} callback
642 * @api private
643 */
644Connection.prototype._close = function(force, callback) {
645 const _this = this;
646 this._closeCalled = true;
647
648 switch (this.readyState) {
649 case 0: // disconnected
650 callback();
651 break;
652
653 case 1: // connected
654 this.readyState = STATES.disconnecting;
655 this.doClose(force, function(err) {
656 if (err) {
657 return callback(err);
658 }
659 _this.onClose(force);
660 callback(null);
661 });
662
663 break;
664 case 2: // connecting
665 this.once('open', function() {
666 _this.close(callback);
667 });
668 break;
669
670 case 3: // disconnecting
671 this.once('close', function() {
672 callback();
673 });
674 break;
675 }
676
677 return this;
678};
679
680/**
681 * Called when the connection closes
682 *
683 * @api private
684 */
685
686Connection.prototype.onClose = function(force) {
687 this.readyState = STATES.disconnected;
688
689 // avoid having the collection subscribe to our event emitter
690 // to prevent 0.3 warning
691 for (const i in this.collections) {
692 if (utils.object.hasOwnProperty(this.collections, i)) {
693 this.collections[i].onClose(force);
694 }
695 }
696
697 this.emit('close', force);
698};
699
700/**
701 * Retrieves a collection, creating it if not cached.
702 *
703 * Not typically needed by applications. Just talk to your collection through your model.
704 *
705 * @param {String} name of the collection
706 * @param {Object} [options] optional collection options
707 * @return {Collection} collection instance
708 * @api public
709 */
710
711Connection.prototype.collection = function(name, options) {
712 options = options ? utils.clone(options) : {};
713 options.$wasForceClosed = this.$wasForceClosed;
714 if (!(name in this.collections)) {
715 this.collections[name] = new Collection(name, this, options);
716 }
717 return this.collections[name];
718};
719
720/**
721 * Defines or retrieves a model.
722 *
723 * var mongoose = require('mongoose');
724 * var db = mongoose.createConnection(..);
725 * db.model('Venue', new Schema(..));
726 * var Ticket = db.model('Ticket', new Schema(..));
727 * var Venue = db.model('Venue');
728 *
729 * _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._
730 *
731 * ####Example:
732 *
733 * var schema = new Schema({ name: String }, { collection: 'actor' });
734 *
735 * // or
736 *
737 * schema.set('collection', 'actor');
738 *
739 * // or
740 *
741 * var collectionName = 'actor'
742 * var M = conn.model('Actor', schema, collectionName)
743 *
744 * @param {String|Function} name the model name or class extending Model
745 * @param {Schema} [schema] a schema. necessary when defining a model
746 * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
747 * @see Mongoose#model #index_Mongoose-model
748 * @return {Model} The compiled model
749 * @api public
750 */
751
752Connection.prototype.model = function(name, schema, collection) {
753 if (!(this instanceof Connection)) {
754 throw new MongooseError('`connection.model()` should not be run with ' +
755 '`new`. If you are doing `new db.model(foo)(bar)`, use ' +
756 '`db.model(foo)(bar)` instead');
757 }
758
759 let fn;
760 if (typeof name === 'function') {
761 fn = name;
762 name = fn.name;
763 }
764
765 // collection name discovery
766 if (typeof schema === 'string') {
767 collection = schema;
768 schema = false;
769 }
770
771 if (utils.isObject(schema) && !schema.instanceOfSchema) {
772 schema = new Schema(schema);
773 }
774 if (schema && !schema.instanceOfSchema) {
775 throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
776 'schema or a POJO');
777 }
778
779 if (this.models[name] && !collection) {
780 // model exists but we are not subclassing with custom collection
781 if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
782 throw new MongooseError.OverwriteModelError(name);
783 }
784 return this.models[name];
785 }
786
787 const opts = {cache: false, connection: this};
788 let model;
789
790 if (schema && schema.instanceOfSchema) {
791 // compile a model
792 model = this.base.model(fn || name, schema, collection, opts);
793
794 // only the first model with this name is cached to allow
795 // for one-offs with custom collection names etc.
796 if (!this.models[name]) {
797 this.models[name] = model;
798 }
799
800 // Errors handled internally, so safe to ignore error
801 model.init(function $modelInitNoop() {});
802
803 return model;
804 }
805
806 if (this.models[name] && collection) {
807 // subclassing current model with alternate collection
808 model = this.models[name];
809 schema = model.prototype.schema;
810 const sub = model.__subclass(this, schema, collection);
811 // do not cache the sub model
812 return sub;
813 }
814
815 // lookup model in mongoose module
816 model = this.base.models[name];
817
818 if (!model) {
819 throw new MongooseError.MissingSchemaError(name);
820 }
821
822 if (this === model.prototype.db
823 && (!collection || collection === model.collection.name)) {
824 // model already uses this connection.
825
826 // only the first model with this name is cached to allow
827 // for one-offs with custom collection names etc.
828 if (!this.models[name]) {
829 this.models[name] = model;
830 }
831
832 return model;
833 }
834 this.models[name] = model.__subclass(this, schema, collection);
835 return this.models[name];
836};
837
838/**
839 * Removes the model named `name` from this connection, if it exists. You can
840 * use this function to clean up any models you created in your tests to
841 * prevent OverwriteModelErrors.
842 *
843 * ####Example:
844 *
845 * conn.model('User', new Schema({ name: String }));
846 * console.log(conn.model('User')); // Model object
847 * conn.deleteModel('User');
848 * console.log(conn.model('User')); // undefined
849 *
850 * // Usually useful in a Mocha `afterEach()` hook
851 * afterEach(function() {
852 * conn.deleteModel(/.+/); // Delete every model
853 * });
854 *
855 * @api public
856 * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
857 * @return {Connection} this
858 */
859
860Connection.prototype.deleteModel = function(name) {
861 if (typeof name === 'string') {
862 const model = this.model(name);
863 if (model == null) {
864 return this;
865 }
866 delete this.models[name];
867 delete this.collections[model.collection.name];
868 delete this.base.modelSchemas[name];
869 } else if (name instanceof RegExp) {
870 const pattern = name;
871 const names = this.modelNames();
872 for (const name of names) {
873 if (pattern.test(name)) {
874 this.deleteModel(name);
875 }
876 }
877 } else {
878 throw new Error('First parameter to `deleteModel()` must be a string ' +
879 'or regexp, got "' + name + '"');
880 }
881
882 return this;
883};
884
885/**
886 * Returns an array of model names created on this connection.
887 * @api public
888 * @return {Array}
889 */
890
891Connection.prototype.modelNames = function() {
892 return Object.keys(this.models);
893};
894
895/**
896 * @brief Returns if the connection requires authentication after it is opened. Generally if a
897 * username and password are both provided than authentication is needed, but in some cases a
898 * password is not required.
899 * @api private
900 * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false.
901 */
902Connection.prototype.shouldAuthenticate = function() {
903 return this.user != null &&
904 (this.pass != null || this.authMechanismDoesNotRequirePassword());
905};
906
907/**
908 * @brief Returns a boolean value that specifies if the current authentication mechanism needs a
909 * password to authenticate according to the auth objects passed into the openUri methods.
910 * @api private
911 * @return {Boolean} true if the authentication mechanism specified in the options object requires
912 * a password, otherwise false.
913 */
914Connection.prototype.authMechanismDoesNotRequirePassword = function() {
915 if (this.options && this.options.auth) {
916 return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0;
917 }
918 return true;
919};
920
921/**
922 * @brief Returns a boolean value that specifies if the provided objects object provides enough
923 * data to authenticate with. Generally this is true if the username and password are both specified
924 * but in some authentication methods, a password is not required for authentication so only a username
925 * is required.
926 * @param {Object} [options] the options object passed into the openUri methods.
927 * @api private
928 * @return {Boolean} true if the provided options object provides enough data to authenticate with,
929 * otherwise false.
930 */
931Connection.prototype.optionsProvideAuthenticationData = function(options) {
932 return (options) &&
933 (options.user) &&
934 ((options.pass) || this.authMechanismDoesNotRequirePassword());
935};
936
937/**
938 * Switches to a different database using the same connection pool.
939 *
940 * Returns a new connection object, with the new db.
941 *
942 * @method useDb
943 * @memberOf Connection
944 * @param {String} name The database name
945 * @return {Connection} New Connection Object
946 * @api public
947 */
948
949/*!
950 * Module exports.
951 */
952
953Connection.STATES = STATES;
954module.exports = Connection;