thoughts/node_modules/mongoose/lib/connection.js
node_modules/mongoose/lib/connection.jsRaw
1/*!
2 * Module dependencies.
3 */
4
5var utils = require('./utils');
6var EventEmitter = require('events').EventEmitter;
7var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native';
8var Schema = require('./schema');
9var Collection = require(driver + '/collection');
10var STATES = require('./connectionstate');
11var MongooseError = require('./error');
12var muri = require('muri');
13var PromiseProvider = require('./promise_provider');
14
15/*!
16 * Protocol prefix regexp.
17 *
18 * @api private
19 */
20
21var rgxProtocol = /^(?:.)+:\/\//;
22
23/*!
24 * A list of authentication mechanisms that don't require a password for authentication.
25 * This is used by the authMechanismDoesNotRequirePassword method.
26 *
27 * @api private
28 */
29var authMechanismsWhichDontRequirePassword = [
30 'MONGODB-X509'
31];
32
33/**
34 * Connection constructor
35 *
36 * For practical reasons, a Connection equals a Db.
37 *
38 * @param {Mongoose} base a mongoose instance
39 * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
40 * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection.
41 * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
42 * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.
43 * @event `disconnecting`: Emitted when `connection.close()` was executed.
44 * @event `disconnected`: Emitted after getting disconnected from the db.
45 * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.
46 * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection.
47 * @event `error`: Emitted when an error occurs on this connection.
48 * @event `fullsetup`: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
49 * @event `all`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
50 * @api public
51 */
52
53function Connection(base) {
54 this.base = base;
55 this.collections = {};
56 this.models = {};
57 this.config = {autoIndex: true};
58 this.replica = false;
59 this.hosts = null;
60 this.host = null;
61 this.port = null;
62 this.user = null;
63 this.pass = null;
64 this.name = null;
65 this.options = null;
66 this.otherDbs = [];
67 this._readyState = STATES.disconnected;
68 this._closeCalled = false;
69 this._hasOpened = false;
70}
71
72/*!
73 * Inherit from EventEmitter
74 */
75
76Connection.prototype.__proto__ = EventEmitter.prototype;
77
78/**
79 * Connection ready state
80 *
81 * - 0 = disconnected
82 * - 1 = connected
83 * - 2 = connecting
84 * - 3 = disconnecting
85 *
86 * Each state change emits its associated event name.
87 *
88 * ####Example
89 *
90 * conn.on('connected', callback);
91 * conn.on('disconnected', callback);
92 *
93 * @property readyState
94 * @api public
95 */
96
97Object.defineProperty(Connection.prototype, 'readyState', {
98 get: function() {
99 return this._readyState;
100 },
101 set: function(val) {
102 if (!(val in STATES)) {
103 throw new Error('Invalid connection state: ' + val);
104 }
105
106 if (this._readyState !== val) {
107 this._readyState = val;
108 // loop over the otherDbs on this connection and change their state
109 for (var i = 0; i < this.otherDbs.length; i++) {
110 this.otherDbs[i].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 * A hash of the collections associated with this connection
124 *
125 * @property collections
126 */
127
128Connection.prototype.collections;
129
130/**
131 * The mongodb.Db instance, set when the connection is opened
132 *
133 * @property db
134 */
135
136Connection.prototype.db;
137
138/**
139 * A hash of the global options that are associated with this connection
140 *
141 * @property config
142 */
143
144Connection.prototype.config;
145
146/**
147 * Opens the connection to MongoDB.
148 *
149 * `options` is a hash with the following possible properties:
150 *
151 * config - passed to the connection config instance
152 * db - passed to the connection db instance
153 * server - passed to the connection server instance(s)
154 * replset - passed to the connection ReplSet instance
155 * user - username for authentication
156 * pass - password for authentication
157 * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
158 *
159 * ####Notes:
160 *
161 * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
162 * Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
163 * See the node-mongodb-native driver instance for options that it understands.
164 *
165 * _Options passed take precedence over options included in connection strings._
166 *
167 * @param {String} connection_string mongodb://uri or the host to which you are connecting
168 * @param {String} [database] database name
169 * @param {Number} [port] database port
170 * @param {Object} [options] options
171 * @param {Function} [callback]
172 * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native
173 * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate
174 * @api public
175 */
176
177Connection.prototype.open = function(host, database, port, options, callback) {
178 var parsed;
179
180 if (typeof database === 'string') {
181 switch (arguments.length) {
182 case 2:
183 port = 27017;
184 break;
185 case 3:
186 switch (typeof port) {
187 case 'function':
188 callback = port;
189 port = 27017;
190 break;
191 case 'object':
192 options = port;
193 port = 27017;
194 break;
195 }
196 break;
197 case 4:
198 if (typeof options === 'function') {
199 callback = options;
200 options = {};
201 }
202 }
203 } else {
204 switch (typeof database) {
205 case 'function':
206 callback = database;
207 database = undefined;
208 break;
209 case 'object':
210 options = database;
211 database = undefined;
212 callback = port;
213 break;
214 }
215
216 if (!rgxProtocol.test(host)) {
217 host = 'mongodb://' + host;
218 }
219
220 try {
221 parsed = muri(host);
222 } catch (err) {
223 this.error(err, callback);
224 return this;
225 }
226
227 database = parsed.db;
228 host = parsed.hosts[0].host || parsed.hosts[0].ipc;
229 port = parsed.hosts[0].port || 27017;
230 }
231
232 this.options = this.parseOptions(options, parsed && parsed.options);
233
234 // make sure we can open
235 if (STATES.disconnected !== this.readyState) {
236 var err = new Error('Trying to open unclosed connection.');
237 err.state = this.readyState;
238 this.error(err, callback);
239 return this;
240 }
241
242 if (!host) {
243 this.error(new Error('Missing hostname.'), callback);
244 return this;
245 }
246
247 if (!database) {
248 this.error(new Error('Missing database name.'), callback);
249 return this;
250 }
251
252 // authentication
253 if (this.optionsProvideAuthenticationData(options)) {
254 this.user = options.user;
255 this.pass = options.pass;
256 } else if (parsed && parsed.auth) {
257 this.user = parsed.auth.user;
258 this.pass = parsed.auth.pass;
259
260 // Check hostname for user/pass
261 } else if (/@/.test(host) && /:/.test(host.split('@')[0])) {
262 host = host.split('@');
263 var auth = host.shift().split(':');
264 host = host.pop();
265 this.user = auth[0];
266 this.pass = auth[1];
267 } else {
268 this.user = this.pass = undefined;
269 }
270
271 // global configuration options
272 if (options && options.config) {
273 this.config.autoIndex = options.config.autoIndex !== false;
274 }
275
276 this.name = database;
277 this.host = host;
278 this.port = port;
279
280 var _this = this;
281 var Promise = PromiseProvider.get();
282 var promise = new Promise.ES6(function(resolve, reject) {
283 _this._open(true, function(error) {
284 callback && callback(error);
285 if (error) {
286 reject(error);
287 if (!callback && !promise.$hasHandler) {
288 _this.emit('error', error);
289 }
290 return;
291 }
292 resolve();
293 });
294 });
295 return promise;
296};
297
298/**
299 * Opens the connection to a replica set.
300 *
301 * ####Example:
302 *
303 * var db = mongoose.createConnection();
304 * db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019");
305 *
306 * The database name and/or auth need only be included in one URI.
307 * The `options` is a hash which is passed to the internal driver connection object.
308 *
309 * Valid `options`
310 *
311 * db - passed to the connection db instance
312 * server - passed to the connection server instance(s)
313 * replset - passed to the connection ReplSetServer instance
314 * user - username for authentication
315 * pass - password for authentication
316 * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
317 * mongos - Boolean - if true, enables High Availability support for mongos
318 *
319 * _Options passed take precedence over options included in connection strings._
320 *
321 * ####Notes:
322 *
323 * _If connecting to multiple mongos servers, set the `mongos` option to true._
324 *
325 * conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
326 *
327 * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
328 * Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
329 * See the node-mongodb-native driver instance for options that it understands.
330 *
331 * _Options passed take precedence over options included in connection strings._
332 *
333 * @param {String} uris comma-separated mongodb:// `URI`s
334 * @param {String} [database] database name if not included in `uris`
335 * @param {Object} [options] passed to the internal driver
336 * @param {Function} [callback]
337 * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native
338 * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate
339 * @api public
340 */
341
342Connection.prototype.openSet = function(uris, database, options, callback) {
343 if (!rgxProtocol.test(uris)) {
344 uris = 'mongodb://' + uris;
345 }
346
347 switch (arguments.length) {
348 case 3:
349 switch (typeof database) {
350 case 'string':
351 this.name = database;
352 break;
353 case 'object':
354 callback = options;
355 options = database;
356 database = null;
357 break;
358 }
359
360 if (typeof options === 'function') {
361 callback = options;
362 options = {};
363 }
364 break;
365 case 2:
366 switch (typeof database) {
367 case 'string':
368 this.name = database;
369 break;
370 case 'function':
371 callback = database;
372 database = null;
373 break;
374 case 'object':
375 options = database;
376 database = null;
377 break;
378 }
379 }
380
381 var parsed;
382 try {
383 parsed = muri(uris);
384 } catch (err) {
385 this.error(err, callback);
386 return this;
387 }
388
389 if (!this.name) {
390 this.name = parsed.db;
391 }
392
393 this.hosts = parsed.hosts;
394 this.options = this.parseOptions(options, parsed && parsed.options);
395 this.replica = true;
396
397 if (!this.name) {
398 this.error(new Error('No database name provided for replica set'), callback);
399 return this;
400 }
401
402 // authentication
403 if (this.optionsProvideAuthenticationData(options)) {
404 this.user = options.user;
405 this.pass = options.pass;
406 } else if (parsed && parsed.auth) {
407 this.user = parsed.auth.user;
408 this.pass = parsed.auth.pass;
409 } else {
410 this.user = this.pass = undefined;
411 }
412
413 // global configuration options
414 if (options && options.config) {
415 this.config.autoIndex = options.config.autoIndex !== false;
416 }
417
418 var _this = this;
419 var Promise = PromiseProvider.get();
420 var promise = new Promise.ES6(function(resolve, reject) {
421 _this._open(true, function(error) {
422 callback && callback(error);
423 if (error) {
424 reject(error);
425 if (!callback && !promise.$hasHandler) {
426 _this.emit('error', error);
427 }
428 return;
429 }
430 resolve();
431 });
432 });
433 return promise;
434};
435
436/**
437 * error
438 *
439 * Graceful error handling, passes error to callback
440 * if available, else emits error on the connection.
441 *
442 * @param {Error} err
443 * @param {Function} callback optional
444 * @api private
445 */
446
447Connection.prototype.error = function(err, callback) {
448 if (callback) {
449 return callback(err);
450 }
451 this.emit('error', err);
452};
453
454/**
455 * Handles opening the connection with the appropriate method based on connection type.
456 *
457 * @param {Function} callback
458 * @api private
459 */
460
461Connection.prototype._open = function(emit, callback) {
462 this.readyState = STATES.connecting;
463 this._closeCalled = false;
464
465 var _this = this;
466
467 var method = this.replica
468 ? 'doOpenSet'
469 : 'doOpen';
470
471 // open connection
472 this[method](function(err) {
473 if (err) {
474 _this.readyState = STATES.disconnected;
475 if (_this._hasOpened) {
476 if (callback) {
477 callback(err);
478 }
479 } else {
480 _this.error(err, emit && callback);
481 }
482 return;
483 }
484
485 _this.onOpen(callback);
486 });
487};
488
489/**
490 * Called when the connection is opened
491 *
492 * @api private
493 */
494
495Connection.prototype.onOpen = function(callback) {
496 var _this = this;
497
498 function open(err, isAuth) {
499 if (err) {
500 _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
501 _this.error(err, callback);
502 return;
503 }
504
505 _this.readyState = STATES.connected;
506
507 // avoid having the collection subscribe to our event emitter
508 // to prevent 0.3 warning
509 for (var i in _this.collections) {
510 if (utils.object.hasOwnProperty(_this.collections, i)) {
511 _this.collections[i].onOpen();
512 }
513 }
514
515 callback && callback();
516 _this.emit('open');
517 }
518
519 // re-authenticate if we're not already connected #3871
520 if (this._readyState !== STATES.connected && this.shouldAuthenticate()) {
521 _this.db.authenticate(_this.user, _this.pass, _this.options.auth, function(err) {
522 open(err, true);
523 });
524 } else {
525 open();
526 }
527};
528
529/**
530 * Closes the connection
531 *
532 * @param {Function} [callback] optional
533 * @return {Connection} self
534 * @api public
535 */
536
537Connection.prototype.close = function(callback) {
538 var _this = this;
539 var Promise = PromiseProvider.get();
540 return new Promise.ES6(function(resolve, reject) {
541 _this._close(function(error) {
542 callback && callback(error);
543 if (error) {
544 reject(error);
545 return;
546 }
547 resolve();
548 });
549 });
550};
551
552/**
553 * Handles closing the connection
554 *
555 * @param {Function} callback
556 * @api private
557 */
558Connection.prototype._close = function(callback) {
559 var _this = this;
560 this._closeCalled = true;
561
562 switch (this.readyState) {
563 case 0: // disconnected
564 callback && callback();
565 break;
566
567 case 1: // connected
568 case 4: // unauthorized
569 this.readyState = STATES.disconnecting;
570 this.doClose(function(err) {
571 if (err) {
572 _this.error(err, callback);
573 } else {
574 _this.onClose();
575 callback && callback();
576 }
577 });
578 break;
579
580 case 2: // connecting
581 this.once('open', function() {
582 _this.close(callback);
583 });
584 break;
585
586 case 3: // disconnecting
587 if (!callback) {
588 break;
589 }
590 this.once('close', function() {
591 callback();
592 });
593 break;
594 }
595
596 return this;
597};
598
599/**
600 * Called when the connection closes
601 *
602 * @api private
603 */
604
605Connection.prototype.onClose = function() {
606 this.readyState = STATES.disconnected;
607
608 // avoid having the collection subscribe to our event emitter
609 // to prevent 0.3 warning
610 for (var i in this.collections) {
611 if (utils.object.hasOwnProperty(this.collections, i)) {
612 this.collections[i].onClose();
613 }
614 }
615
616 this.emit('close');
617};
618
619/**
620 * Retrieves a collection, creating it if not cached.
621 *
622 * Not typically needed by applications. Just talk to your collection through your model.
623 *
624 * @param {String} name of the collection
625 * @param {Object} [options] optional collection options
626 * @return {Collection} collection instance
627 * @api public
628 */
629
630Connection.prototype.collection = function(name, options) {
631 if (!(name in this.collections)) {
632 this.collections[name] = new Collection(name, this, options);
633 }
634 return this.collections[name];
635};
636
637/**
638 * Defines or retrieves a model.
639 *
640 * var mongoose = require('mongoose');
641 * var db = mongoose.createConnection(..);
642 * db.model('Venue', new Schema(..));
643 * var Ticket = db.model('Ticket', new Schema(..));
644 * var Venue = db.model('Venue');
645 *
646 * _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._
647 *
648 * ####Example:
649 *
650 * var schema = new Schema({ name: String }, { collection: 'actor' });
651 *
652 * // or
653 *
654 * schema.set('collection', 'actor');
655 *
656 * // or
657 *
658 * var collectionName = 'actor'
659 * var M = conn.model('Actor', schema, collectionName)
660 *
661 * @param {String} name the model name
662 * @param {Schema} [schema] a schema. necessary when defining a model
663 * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
664 * @see Mongoose#model #index_Mongoose-model
665 * @return {Model} The compiled model
666 * @api public
667 */
668
669Connection.prototype.model = function(name, schema, collection) {
670 // collection name discovery
671 if (typeof schema === 'string') {
672 collection = schema;
673 schema = false;
674 }
675
676 if (utils.isObject(schema) && !schema.instanceOfSchema) {
677 schema = new Schema(schema);
678 }
679
680 if (this.models[name] && !collection) {
681 // model exists but we are not subclassing with custom collection
682 if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
683 throw new MongooseError.OverwriteModelError(name);
684 }
685 return this.models[name];
686 }
687
688 var opts = {cache: false, connection: this};
689 var model;
690
691 if (schema && schema.instanceOfSchema) {
692 // compile a model
693 model = this.base.model(name, schema, collection, opts);
694
695 // only the first model with this name is cached to allow
696 // for one-offs with custom collection names etc.
697 if (!this.models[name]) {
698 this.models[name] = model;
699 }
700
701 model.init();
702 return model;
703 }
704
705 if (this.models[name] && collection) {
706 // subclassing current model with alternate collection
707 model = this.models[name];
708 schema = model.prototype.schema;
709 var sub = model.__subclass(this, schema, collection);
710 // do not cache the sub model
711 return sub;
712 }
713
714 // lookup model in mongoose module
715 model = this.base.models[name];
716
717 if (!model) {
718 throw new MongooseError.MissingSchemaError(name);
719 }
720
721 if (this === model.prototype.db
722 && (!collection || collection === model.collection.name)) {
723 // model already uses this connection.
724
725 // only the first model with this name is cached to allow
726 // for one-offs with custom collection names etc.
727 if (!this.models[name]) {
728 this.models[name] = model;
729 }
730
731 return model;
732 }
733 this.models[name] = model.__subclass(this, schema, collection);
734 return this.models[name];
735};
736
737/**
738 * Returns an array of model names created on this connection.
739 * @api public
740 * @return {Array}
741 */
742
743Connection.prototype.modelNames = function() {
744 return Object.keys(this.models);
745};
746
747/**
748 * @brief Returns if the connection requires authentication after it is opened. Generally if a
749 * username and password are both provided than authentication is needed, but in some cases a
750 * password is not required.
751 * @api private
752 * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false.
753 */
754Connection.prototype.shouldAuthenticate = function() {
755 return (this.user !== null && this.user !== void 0) &&
756 ((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword());
757};
758
759/**
760 * @brief Returns a boolean value that specifies if the current authentication mechanism needs a
761 * password to authenticate according to the auth objects passed into the open/openSet methods.
762 * @api private
763 * @return {Boolean} true if the authentication mechanism specified in the options object requires
764 * a password, otherwise false.
765 */
766Connection.prototype.authMechanismDoesNotRequirePassword = function() {
767 if (this.options && this.options.auth) {
768 return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0;
769 }
770 return true;
771};
772
773/**
774 * @brief Returns a boolean value that specifies if the provided objects object provides enough
775 * data to authenticate with. Generally this is true if the username and password are both specified
776 * but in some authentication methods, a password is not required for authentication so only a username
777 * is required.
778 * @param {Object} [options] the options object passed into the open/openSet methods.
779 * @api private
780 * @return {Boolean} true if the provided options object provides enough data to authenticate with,
781 * otherwise false.
782 */
783Connection.prototype.optionsProvideAuthenticationData = function(options) {
784 return (options) &&
785 (options.user) &&
786 ((options.pass) || this.authMechanismDoesNotRequirePassword());
787};
788
789/*!
790 * Module exports.
791 */
792
793Connection.STATES = STATES;
794module.exports = Connection;