1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | const EventEmitter = require('events').EventEmitter;
|
8 | const Schema = require('./schema');
|
9 | const Collection = require('./driver').get().Collection;
|
10 | const STATES = require('./connectionstate');
|
11 | const MongooseError = require('./error');
|
12 | const PromiseProvider = require('./promise_provider');
|
13 | const applyPlugins = require('./helpers/schema/applyPlugins');
|
14 | const get = require('./helpers/get');
|
15 | const mongodb = require('mongodb');
|
16 | const utils = require('./utils');
|
17 |
|
18 | const parseConnectionString = require('mongodb-core').parseConnectionString;
|
19 |
|
20 | /*!
|
21 | * A list of authentication mechanisms that don't require a password for authentication.
|
22 | * This is used by the authMechanismDoesNotRequirePassword method.
|
23 | *
|
24 | * @api private
|
25 | */
|
26 | const noPasswordAuthMechanisms = [
|
27 | 'MONGODB-X509'
|
28 | ];
|
29 |
|
30 | /**
|
31 | * Connection constructor
|
32 | *
|
33 | * For practical reasons, a Connection equals a Db.
|
34 | *
|
35 | * @param {Mongoose} base a mongoose instance
|
36 | * @inherits NodeJS EventEmitter http:
|
37 | * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection.
|
38 | * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
|
39 | * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.
|
40 | * @event `disconnecting`: Emitted when `connection.close()` was executed.
|
41 | * @event `disconnected`: Emitted after getting disconnected from the db.
|
42 | * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.
|
43 | * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection.
|
44 | * @event `error`: Emitted when an error occurs on this connection.
|
45 | * @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string.
|
46 | * @api public
|
47 | */
|
48 |
|
49 | function 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 = [];
|
57 | this.relatedDbs = {};
|
58 | this.states = STATES;
|
59 | this._readyState = STATES.disconnected;
|
60 | this._closeCalled = false;
|
61 | this._hasOpened = false;
|
62 | this.plugins = [];
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | Connection.prototype.__proto__ = EventEmitter.prototype;
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 | Object.defineProperty(Connection.prototype, 'readyState', {
|
93 | get: function() {
|
94 | return this._readyState;
|
95 | },
|
96 | set: function(val) {
|
97 | if (!(val in STATES)) {
|
98 | throw new Error('Invalid connection state: ' + val);
|
99 | }
|
100 |
|
101 | if (this._readyState !== val) {
|
102 | this._readyState = val;
|
103 |
|
104 | for (let i = 0; i < this.otherDbs.length; i++) {
|
105 | this.otherDbs[i].readyState = val;
|
106 | }
|
107 |
|
108 |
|
109 | for (const k in this.relatedDbs) {
|
110 | this.relatedDbs[k].readyState = val;
|
111 | }
|
112 |
|
113 | if (STATES.connected === val) {
|
114 | this._hasOpened = true;
|
115 | }
|
116 |
|
117 | this.emit(STATES[val]);
|
118 | }
|
119 | }
|
120 | });
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 |
|
133 |
|
134 | Connection.prototype.get = function(key) {
|
135 | return get(this.options, key);
|
136 | };
|
137 |
|
138 | /**
|
139 | * Sets the value of the option `key`. Equivalent to `conn.options[key] = val`
|
140 | *
|
141 | * Supported options include:
|
142 | *
|
143 | * - `maxTimeMS`: Set [`maxTimeMS`](/docs/api.html#query_Query-maxTimeMS) for all queries on this connection.
|
144 | * - `useFindAndModify`: Set to `false` to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#-findandmodify-)
|
145 | *
|
146 | * ####Example:
|
147 | *
|
148 | * conn.set('test', 'foo');
|
149 | * conn.get('test'); // 'foo'
|
150 | * conn.options.test; // 'foo'
|
151 | *
|
152 | * @param {String} key
|
153 | * @param {Any} val
|
154 | * @method set
|
155 | * @api public
|
156 | */
|
157 |
|
158 | Connection.prototype.set = function(key, val) {
|
159 | this.options = this.options || {};
|
160 | this.options[key] = val;
|
161 | return val;
|
162 | };
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 | Connection.prototype.collections;
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 |
|
181 |
|
182 |
|
183 |
|
184 |
|
185 |
|
186 |
|
187 |
|
188 | Connection.prototype.name;
|
189 |
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 |
|
206 |
|
207 | Object.defineProperty(Connection.prototype, 'plugins', {
|
208 | configurable: false,
|
209 | enumerable: true,
|
210 | writable: true
|
211 | });
|
212 |
|
213 |
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 | Object.defineProperty(Connection.prototype, 'host', {
|
228 | configurable: true,
|
229 | enumerable: true,
|
230 | writable: true
|
231 | });
|
232 |
|
233 |
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 | Object.defineProperty(Connection.prototype, 'port', {
|
248 | configurable: true,
|
249 | enumerable: true,
|
250 | writable: true
|
251 | });
|
252 |
|
253 |
|
254 |
|
255 |
|
256 |
|
257 |
|
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 | Object.defineProperty(Connection.prototype, 'user', {
|
267 | configurable: true,
|
268 | enumerable: true,
|
269 | writable: true
|
270 | });
|
271 |
|
272 |
|
273 |
|
274 |
|
275 |
|
276 |
|
277 |
|
278 |
|
279 |
|
280 |
|
281 |
|
282 |
|
283 |
|
284 |
|
285 | Object.defineProperty(Connection.prototype, 'pass', {
|
286 | configurable: true,
|
287 | enumerable: true,
|
288 | writable: true
|
289 | });
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 |
|
298 |
|
299 |
|
300 | Connection.prototype.db;
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 |
|
310 |
|
311 | Connection.prototype.config;
|
312 |
|
313 |
|
314 |
|
315 |
|
316 |
|
317 |
|
318 |
|
319 |
|
320 |
|
321 |
|
322 |
|
323 |
|
324 |
|
325 |
|
326 |
|
327 |
|
328 | Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) {
|
329 | if (typeof options === 'function') {
|
330 | cb = options;
|
331 | options = {};
|
332 | }
|
333 | this.db.createCollection(collection, options, cb);
|
334 | });
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 |
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 | Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) {
|
362 | if (typeof options === 'function') {
|
363 | cb = options;
|
364 | options = null;
|
365 | }
|
366 | const session = this.client.startSession(options);
|
367 | cb(null, session);
|
368 | });
|
369 |
|
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 |
|
380 |
|
381 | Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) {
|
382 | this.db.dropCollection(collection, cb);
|
383 | });
|
384 |
|
385 |
|
386 |
|
387 |
|
388 |
|
389 |
|
390 |
|
391 |
|
392 |
|
393 |
|
394 |
|
395 |
|
396 |
|
397 |
|
398 |
|
399 |
|
400 |
|
401 | Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
|
402 |
|
403 |
|
404 |
|
405 |
|
406 | for (const name of Object.keys(this.models)) {
|
407 | delete this.models[name].$init;
|
408 | }
|
409 | this.db.dropDatabase(cb);
|
410 | });
|
411 |
|
412 |
|
413 |
|
414 |
|
415 |
|
416 | function _wrapConnHelper(fn) {
|
417 | return function() {
|
418 | const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null;
|
419 | const argsWithoutCb = typeof cb === 'function' ?
|
420 | Array.prototype.slice.call(arguments, 0, arguments.length - 1) :
|
421 | Array.prototype.slice.call(arguments);
|
422 | return utils.promiseOrCallback(cb, cb => {
|
423 | if (this.readyState !== STATES.connected) {
|
424 | this.once('open', function() {
|
425 | fn.apply(this, argsWithoutCb.concat([cb]));
|
426 | });
|
427 | } else {
|
428 | fn.apply(this, argsWithoutCb.concat([cb]));
|
429 | }
|
430 | });
|
431 | };
|
432 | }
|
433 |
|
434 |
|
435 |
|
436 |
|
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 | Connection.prototype.error = function(err, callback) {
|
446 | if (callback) {
|
447 | callback(err);
|
448 | return null;
|
449 | }
|
450 | if (this.listeners('error').length > 0) {
|
451 | this.emit('error', err);
|
452 | }
|
453 | return Promise.reject(err);
|
454 | };
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 |
|
462 | Connection.prototype.onOpen = function() {
|
463 | this.readyState = STATES.connected;
|
464 |
|
465 |
|
466 |
|
467 | for (const i in this.collections) {
|
468 | if (utils.object.hasOwnProperty(this.collections, i)) {
|
469 | this.collections[i].onOpen();
|
470 | }
|
471 | }
|
472 |
|
473 | this.emit('open');
|
474 | };
|
475 |
|
476 |
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 |
|
483 |
|
484 |
|
485 |
|
486 | Connection.prototype.openUri = function(uri, options, callback) {
|
487 | this.readyState = STATES.connecting;
|
488 | this._closeCalled = false;
|
489 |
|
490 | if (typeof options === 'function') {
|
491 | callback = options;
|
492 | options = null;
|
493 | }
|
494 |
|
495 | if (['string', 'number'].indexOf(typeof options) !== -1) {
|
496 | throw new MongooseError('Mongoose 5.x no longer supports ' +
|
497 | '`mongoose.connect(host, dbname, port)` or ' +
|
498 | '`mongoose.createConnection(host, dbname, port)`. See ' +
|
499 | 'http://mongoosejs.com/docs/connections.html for supported connection syntax');
|
500 | }
|
501 |
|
502 | if (typeof uri !== 'string') {
|
503 | throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
|
504 | `string, got "${typeof uri}". Make sure the first parameter to ` +
|
505 | '`mongoose.connect()` or `mongoose.createConnection()` is a string.');
|
506 | }
|
507 |
|
508 | const Promise = PromiseProvider.get();
|
509 | const _this = this;
|
510 |
|
511 | if (options) {
|
512 | options = utils.clone(options);
|
513 | const autoIndex = options.config && options.config.autoIndex != null ?
|
514 | options.config.autoIndex :
|
515 | options.autoIndex;
|
516 | if (autoIndex != null) {
|
517 | this.config.autoIndex = autoIndex !== false;
|
518 | delete options.config;
|
519 | delete options.autoIndex;
|
520 | }
|
521 |
|
522 | if ('autoCreate' in options) {
|
523 | this.config.autoCreate = !!options.autoCreate;
|
524 | delete options.autoCreate;
|
525 | }
|
526 | if ('useCreateIndex' in options) {
|
527 | this.config.useCreateIndex = !!options.useCreateIndex;
|
528 | delete options.useCreateIndex;
|
529 | }
|
530 |
|
531 | if ('useFindAndModify' in options) {
|
532 | this.config.useFindAndModify = !!options.useFindAndModify;
|
533 | delete options.useFindAndModify;
|
534 | }
|
535 |
|
536 |
|
537 | if (options.user || options.pass) {
|
538 | options.auth = options.auth || {};
|
539 | options.auth.user = options.user;
|
540 | options.auth.password = options.pass;
|
541 |
|
542 | this.user = options.user;
|
543 | this.pass = options.pass;
|
544 | }
|
545 | delete options.user;
|
546 | delete options.pass;
|
547 |
|
548 | if (options.bufferCommands != null) {
|
549 | options.bufferMaxEntries = 0;
|
550 | this.config.bufferCommands = options.bufferCommands;
|
551 | delete options.bufferCommands;
|
552 | }
|
553 |
|
554 | if (options.useMongoClient != null) {
|
555 | handleUseMongoClient(options);
|
556 | }
|
557 | } else {
|
558 | options = {};
|
559 | }
|
560 |
|
561 | this._connectionOptions = options;
|
562 | const dbName = options.dbName;
|
563 | if (dbName != null) {
|
564 | this.$dbName = dbName;
|
565 | }
|
566 | delete options.dbName;
|
567 |
|
568 | if (!('promiseLibrary' in options)) {
|
569 | options.promiseLibrary = PromiseProvider.get();
|
570 | }
|
571 | if (!('useNewUrlParser' in options)) {
|
572 | if ('useNewUrlParser' in this.base.options) {
|
573 | options.useNewUrlParser = this.base.options.useNewUrlParser;
|
574 | } else {
|
575 | options.useNewUrlParser = false;
|
576 | }
|
577 | }
|
578 |
|
579 | const parsePromise = new Promise((resolve, reject) => {
|
580 | parseConnectionString(uri, options, (err, parsed) => {
|
581 | if (err) {
|
582 | return reject(err);
|
583 | }
|
584 | this.name = dbName != null ? dbName : get(parsed, 'auth.db', null);
|
585 | this.host = get(parsed, 'hosts.0.host', 'localhost');
|
586 | this.port = get(parsed, 'hosts.0.port', 27017);
|
587 | this.user = this.user || get(parsed, 'auth.username');
|
588 | this.pass = this.pass || get(parsed, 'auth.password');
|
589 | resolve();
|
590 | });
|
591 | });
|
592 |
|
593 | const promise = new Promise((resolve, reject) => {
|
594 | const client = new mongodb.MongoClient(uri, options);
|
595 | _this.client = client;
|
596 | client.connect(function(error) {
|
597 | if (error) {
|
598 | _this.readyState = STATES.disconnected;
|
599 | return reject(error);
|
600 | }
|
601 |
|
602 | const db = dbName != null ? client.db(dbName) : client.db();
|
603 | _this.db = db;
|
604 |
|
605 |
|
606 | db.on('reconnect', function() {
|
607 |
|
608 |
|
609 |
|
610 |
|
611 | if (_this.readyState !== STATES.connected) {
|
612 | _this.readyState = STATES.connected;
|
613 | _this.emit('reconnect');
|
614 | _this.emit('reconnected');
|
615 | }
|
616 | });
|
617 | db.s.topology.on('reconnectFailed', function() {
|
618 | _this.emit('reconnectFailed');
|
619 | });
|
620 | db.s.topology.on('left', function(data) {
|
621 | _this.emit('left', data);
|
622 | });
|
623 | db.s.topology.on('joined', function(data) {
|
624 | _this.emit('joined', data);
|
625 | });
|
626 | db.s.topology.on('fullsetup', function(data) {
|
627 | _this.emit('fullsetup', data);
|
628 | });
|
629 | db.s.topology.on('attemptReconnect', function() {
|
630 | _this.emit('attemptReconnect');
|
631 | });
|
632 | db.on('close', function() {
|
633 |
|
634 | _this.readyState = STATES.disconnected;
|
635 | });
|
636 | client.on('left', function() {
|
637 | if (_this.readyState === STATES.connected &&
|
638 | get(db, 's.topology.s.coreTopology.s.replicaSetState.topologyType') === 'ReplicaSetNoPrimary') {
|
639 | _this.readyState = STATES.disconnected;
|
640 | }
|
641 | });
|
642 | db.on('timeout', function() {
|
643 | _this.emit('timeout');
|
644 | });
|
645 |
|
646 | delete _this.then;
|
647 | delete _this.catch;
|
648 | _this.readyState = STATES.connected;
|
649 |
|
650 | for (const i in _this.collections) {
|
651 | if (utils.object.hasOwnProperty(_this.collections, i)) {
|
652 | _this.collections[i].onOpen();
|
653 | }
|
654 | }
|
655 |
|
656 | resolve(_this);
|
657 | _this.emit('open');
|
658 | });
|
659 | });
|
660 |
|
661 | this.$initialConnection = Promise.all([promise, parsePromise]).
|
662 | then(res => res[0]).
|
663 | catch(err => {
|
664 | if (this.listeners('error').length > 0) {
|
665 | process.nextTick(() => this.emit('error', err));
|
666 | }
|
667 | throw err;
|
668 | });
|
669 | this.then = function(resolve, reject) {
|
670 | return this.$initialConnection.then(resolve, reject);
|
671 | };
|
672 | this.catch = function(reject) {
|
673 | return this.$initialConnection.catch(reject);
|
674 | };
|
675 |
|
676 | if (callback != null) {
|
677 | this.$initialConnection = this.$initialConnection.then(
|
678 | () => callback(null, this),
|
679 | err => callback(err)
|
680 | );
|
681 | }
|
682 |
|
683 | return this;
|
684 | };
|
685 |
|
686 |
|
687 |
|
688 |
|
689 |
|
690 | const handleUseMongoClient = function handleUseMongoClient(options) {
|
691 | console.warn('WARNING: The `useMongoClient` option is no longer ' +
|
692 | 'necessary in mongoose 5.x, please remove it.');
|
693 | const stack = new Error().stack;
|
694 | console.warn(stack.substr(stack.indexOf('\n') + 1));
|
695 | delete options.useMongoClient;
|
696 | };
|
697 |
|
698 |
|
699 |
|
700 |
|
701 |
|
702 |
|
703 |
|
704 |
|
705 |
|
706 |
|
707 | Connection.prototype.close = function(force, callback) {
|
708 | if (typeof force === 'function') {
|
709 | callback = force;
|
710 | force = false;
|
711 | }
|
712 |
|
713 | this.$wasForceClosed = !!force;
|
714 |
|
715 | return utils.promiseOrCallback(callback, cb => {
|
716 | this._close(force, cb);
|
717 | });
|
718 | };
|
719 |
|
720 |
|
721 |
|
722 |
|
723 |
|
724 |
|
725 |
|
726 |
|
727 | Connection.prototype._close = function(force, callback) {
|
728 | const _this = this;
|
729 | this._closeCalled = true;
|
730 |
|
731 | switch (this.readyState) {
|
732 | case STATES.disconnected:
|
733 | callback();
|
734 | break;
|
735 |
|
736 | case STATES.connected:
|
737 | this.readyState = STATES.disconnecting;
|
738 | this.doClose(force, function(err) {
|
739 | if (err) {
|
740 | return callback(err);
|
741 | }
|
742 | _this.onClose(force);
|
743 | callback(null);
|
744 | });
|
745 |
|
746 | break;
|
747 | case STATES.connecting:
|
748 | this.once('open', function() {
|
749 | _this.close(callback);
|
750 | });
|
751 | break;
|
752 |
|
753 | case STATES.disconnecting:
|
754 | this.once('close', function() {
|
755 | callback();
|
756 | });
|
757 | break;
|
758 | }
|
759 |
|
760 | return this;
|
761 | };
|
762 |
|
763 |
|
764 |
|
765 |
|
766 |
|
767 |
|
768 |
|
769 | Connection.prototype.onClose = function(force) {
|
770 | this.readyState = STATES.disconnected;
|
771 |
|
772 |
|
773 |
|
774 | for (const i in this.collections) {
|
775 | if (utils.object.hasOwnProperty(this.collections, i)) {
|
776 | this.collections[i].onClose(force);
|
777 | }
|
778 | }
|
779 |
|
780 | this.emit('close', force);
|
781 | };
|
782 |
|
783 |
|
784 |
|
785 |
|
786 |
|
787 |
|
788 |
|
789 |
|
790 |
|
791 |
|
792 |
|
793 |
|
794 | Connection.prototype.collection = function(name, options) {
|
795 | options = options ? utils.clone(options) : {};
|
796 | options.$wasForceClosed = this.$wasForceClosed;
|
797 | if (!(name in this.collections)) {
|
798 | this.collections[name] = new Collection(name, this, options);
|
799 | }
|
800 | return this.collections[name];
|
801 | };
|
802 |
|
803 |
|
804 |
|
805 |
|
806 |
|
807 |
|
808 |
|
809 |
|
810 |
|
811 |
|
812 |
|
813 |
|
814 |
|
815 |
|
816 |
|
817 |
|
818 |
|
819 |
|
820 |
|
821 |
|
822 | Connection.prototype.plugin = function(fn, opts) {
|
823 | this.plugins.push([fn, opts]);
|
824 | return this;
|
825 | };
|
826 |
|
827 |
|
828 |
|
829 |
|
830 |
|
831 |
|
832 |
|
833 |
|
834 |
|
835 |
|
836 |
|
837 |
|
838 |
|
839 |
|
840 |
|
841 |
|
842 |
|
843 |
|
844 |
|
845 |
|
846 |
|
847 |
|
848 |
|
849 |
|
850 |
|
851 |
|
852 |
|
853 |
|
854 |
|
855 |
|
856 |
|
857 |
|
858 |
|
859 | Connection.prototype.model = function(name, schema, collection) {
|
860 | if (!(this instanceof Connection)) {
|
861 | throw new MongooseError('`connection.model()` should not be run with ' +
|
862 | '`new`. If you are doing `new db.model(foo)(bar)`, use ' +
|
863 | '`db.model(foo)(bar)` instead');
|
864 | }
|
865 |
|
866 | let fn;
|
867 | if (typeof name === 'function') {
|
868 | fn = name;
|
869 | name = fn.name;
|
870 | }
|
871 |
|
872 |
|
873 | if (typeof schema === 'string') {
|
874 | collection = schema;
|
875 | schema = false;
|
876 | }
|
877 |
|
878 | if (utils.isObject(schema) && !schema.instanceOfSchema) {
|
879 | schema = new Schema(schema);
|
880 | }
|
881 | if (schema && !schema.instanceOfSchema) {
|
882 | throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
|
883 | 'schema or a POJO');
|
884 | }
|
885 |
|
886 | if (this.models[name] && !collection) {
|
887 |
|
888 | if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
|
889 | throw new MongooseError.OverwriteModelError(name);
|
890 | }
|
891 | return this.models[name];
|
892 | }
|
893 |
|
894 | const opts = {cache: false, connection: this};
|
895 | let model;
|
896 |
|
897 | if (schema && schema.instanceOfSchema) {
|
898 | applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied');
|
899 |
|
900 |
|
901 | model = this.base.model(fn || name, schema, collection, opts);
|
902 |
|
903 |
|
904 |
|
905 | if (!this.models[name]) {
|
906 | this.models[name] = model;
|
907 | }
|
908 |
|
909 |
|
910 | model.init(function $modelInitNoop() {});
|
911 |
|
912 | return model;
|
913 | }
|
914 |
|
915 | if (this.models[name] && collection) {
|
916 |
|
917 | model = this.models[name];
|
918 | schema = model.prototype.schema;
|
919 | const sub = model.__subclass(this, schema, collection);
|
920 |
|
921 | return sub;
|
922 | }
|
923 |
|
924 |
|
925 | model = this.base.models[name];
|
926 |
|
927 | if (!model) {
|
928 | throw new MongooseError.MissingSchemaError(name);
|
929 | }
|
930 |
|
931 | if (this === model.prototype.db
|
932 | && (!collection || collection === model.collection.name)) {
|
933 |
|
934 |
|
935 |
|
936 |
|
937 | if (!this.models[name]) {
|
938 | this.models[name] = model;
|
939 | }
|
940 |
|
941 | return model;
|
942 | }
|
943 | this.models[name] = model.__subclass(this, schema, collection);
|
944 | return this.models[name];
|
945 | };
|
946 |
|
947 |
|
948 |
|
949 |
|
950 |
|
951 |
|
952 |
|
953 |
|
954 |
|
955 |
|
956 |
|
957 |
|
958 |
|
959 |
|
960 |
|
961 |
|
962 |
|
963 |
|
964 |
|
965 |
|
966 |
|
967 |
|
968 |
|
969 | Connection.prototype.deleteModel = function(name) {
|
970 | if (typeof name === 'string') {
|
971 | const model = this.model(name);
|
972 | if (model == null) {
|
973 | return this;
|
974 | }
|
975 | delete this.models[name];
|
976 | delete this.collections[model.collection.name];
|
977 | delete this.base.modelSchemas[name];
|
978 | } else if (name instanceof RegExp) {
|
979 | const pattern = name;
|
980 | const names = this.modelNames();
|
981 | for (const name of names) {
|
982 | if (pattern.test(name)) {
|
983 | this.deleteModel(name);
|
984 | }
|
985 | }
|
986 | } else {
|
987 | throw new Error('First parameter to `deleteModel()` must be a string ' +
|
988 | 'or regexp, got "' + name + '"');
|
989 | }
|
990 |
|
991 | return this;
|
992 | };
|
993 |
|
994 |
|
995 |
|
996 |
|
997 |
|
998 |
|
999 |
|
1000 | Connection.prototype.modelNames = function() {
|
1001 | return Object.keys(this.models);
|
1002 | };
|
1003 |
|
1004 |
|
1005 |
|
1006 |
|
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 | Connection.prototype.shouldAuthenticate = function() {
|
1012 | return this.user != null &&
|
1013 | (this.pass != null || this.authMechanismDoesNotRequirePassword());
|
1014 | };
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 |
|
1020 |
|
1021 |
|
1022 |
|
1023 | Connection.prototype.authMechanismDoesNotRequirePassword = function() {
|
1024 | if (this.options && this.options.auth) {
|
1025 | return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0;
|
1026 | }
|
1027 | return true;
|
1028 | };
|
1029 |
|
1030 |
|
1031 |
|
1032 |
|
1033 |
|
1034 |
|
1035 |
|
1036 |
|
1037 |
|
1038 |
|
1039 |
|
1040 | Connection.prototype.optionsProvideAuthenticationData = function(options) {
|
1041 | return (options) &&
|
1042 | (options.user) &&
|
1043 | ((options.pass) || this.authMechanismDoesNotRequirePassword());
|
1044 | };
|
1045 |
|
1046 |
|
1047 |
|
1048 |
|
1049 |
|
1050 |
|
1051 |
|
1052 |
|
1053 |
|
1054 |
|
1055 |
|
1056 |
|
1057 |
|
1058 |
|
1059 |
|
1060 |
|
1061 |
|
1062 |
|
1063 |
|
1064 | Connection.STATES = STATES;
|
1065 | module.exports = Connection;
|