connection.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseConnection = require('../../connection');
  6. const STATES = require('../../connectionstate');
  7. /**
  8. * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
  9. *
  10. * @inherits Connection
  11. * @api private
  12. */
  13. function NativeConnection() {
  14. MongooseConnection.apply(this, arguments);
  15. this._listening = false;
  16. }
  17. /**
  18. * Expose the possible connection states.
  19. * @api public
  20. */
  21. NativeConnection.STATES = STATES;
  22. /*!
  23. * Inherits from Connection.
  24. */
  25. NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
  26. /**
  27. * Switches to a different database using the same connection pool.
  28. *
  29. * Returns a new connection object, with the new db. If you set the `useCache`
  30. * option, `useDb()` will cache connections by `name`.
  31. *
  32. * **Note:** Calling `close()` on a `useDb()` connection will close the base connection as well.
  33. *
  34. * @param {String} name The database name
  35. * @param {Object} [options]
  36. * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
  37. * @param {Boolean} [options.noListener=false] If true, the new connection object won't listen to any events on the base connection. This is better for memory usage in cases where you're calling `useDb()` for every request.
  38. * @return {Connection} New Connection Object
  39. * @api public
  40. */
  41. NativeConnection.prototype.useDb = function(name, options) {
  42. // Return immediately if cached
  43. options = options || {};
  44. if (options.useCache && this.relatedDbs[name]) {
  45. return this.relatedDbs[name];
  46. }
  47. // we have to manually copy all of the attributes...
  48. const newConn = new this.constructor();
  49. newConn.name = name;
  50. newConn.base = this.base;
  51. newConn.collections = {};
  52. newConn.models = {};
  53. newConn.replica = this.replica;
  54. newConn.config = Object.assign({}, this.config, newConn.config);
  55. newConn.name = this.name;
  56. newConn.options = this.options;
  57. newConn._readyState = this._readyState;
  58. newConn._closeCalled = this._closeCalled;
  59. newConn._hasOpened = this._hasOpened;
  60. newConn._listening = false;
  61. newConn.host = this.host;
  62. newConn.port = this.port;
  63. newConn.user = this.user;
  64. newConn.pass = this.pass;
  65. // First, when we create another db object, we are not guaranteed to have a
  66. // db object to work with. So, in the case where we have a db object and it
  67. // is connected, we can just proceed with setting everything up. However, if
  68. // we do not have a db or the state is not connected, then we need to wait on
  69. // the 'open' event of the connection before doing the rest of the setup
  70. // the 'connected' event is the first time we'll have access to the db object
  71. const _this = this;
  72. newConn.client = _this.client;
  73. if (this.db && this._readyState === STATES.connected) {
  74. wireup();
  75. } else {
  76. this.once('connected', wireup);
  77. }
  78. function wireup() {
  79. newConn.client = _this.client;
  80. const _opts = {};
  81. if (options.hasOwnProperty('noListener')) {
  82. _opts.noListener = options.noListener;
  83. }
  84. newConn.db = _this.client.db(name, _opts);
  85. newConn.onOpen();
  86. // setup the events appropriately
  87. if (options.noListener !== true) {
  88. listen(newConn);
  89. }
  90. }
  91. newConn.name = name;
  92. // push onto the otherDbs stack, this is used when state changes
  93. if (options.noListener !== true) {
  94. this.otherDbs.push(newConn);
  95. }
  96. newConn.otherDbs.push(this);
  97. // push onto the relatedDbs cache, this is used when state changes
  98. if (options && options.useCache) {
  99. this.relatedDbs[newConn.name] = newConn;
  100. newConn.relatedDbs = this.relatedDbs;
  101. }
  102. return newConn;
  103. };
  104. /*!
  105. * Register listeners for important events and bubble appropriately.
  106. */
  107. function listen(conn) {
  108. if (conn._listening) {
  109. return;
  110. }
  111. conn._listening = true;
  112. conn.client.on('close', function(force) {
  113. if (conn._closeCalled) {
  114. return;
  115. }
  116. conn._closeCalled = conn.client._closeCalled;
  117. // the driver never emits an `open` event. auto_reconnect still
  118. // emits a `close` event but since we never get another
  119. // `open` we can't emit close
  120. if (conn.db.serverConfig.autoReconnect) {
  121. conn.readyState = STATES.disconnected;
  122. conn.emit('close');
  123. return;
  124. }
  125. conn.onClose(force);
  126. });
  127. conn.client.on('error', function(err) {
  128. conn.emit('error', err);
  129. });
  130. if (!conn.client.s.options.useUnifiedTopology) {
  131. conn.db.on('reconnect', function() {
  132. conn.readyState = STATES.connected;
  133. conn.emit('reconnect');
  134. conn.emit('reconnected');
  135. conn.onOpen();
  136. });
  137. conn.db.on('open', function(err, db) {
  138. if (STATES.disconnected === conn.readyState && db && db.databaseName) {
  139. conn.readyState = STATES.connected;
  140. conn.emit('reconnect');
  141. conn.emit('reconnected');
  142. }
  143. });
  144. }
  145. conn.client.on('timeout', function(err) {
  146. conn.emit('timeout', err);
  147. });
  148. conn.client.on('parseError', function(err) {
  149. conn.emit('parseError', err);
  150. });
  151. }
  152. /**
  153. * Closes the connection
  154. *
  155. * @param {Boolean} [force]
  156. * @param {Function} [fn]
  157. * @return {Connection} this
  158. * @api private
  159. */
  160. NativeConnection.prototype.doClose = function(force, fn) {
  161. if (this.client == null) {
  162. process.nextTick(() => fn());
  163. return this;
  164. }
  165. this.client.close(force, (err, res) => {
  166. // Defer because the driver will wait at least 1ms before finishing closing
  167. // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030.
  168. // If there's queued operations, you may still get some background work
  169. // after the callback is called.
  170. setTimeout(() => fn(err, res), 1);
  171. });
  172. return this;
  173. };
  174. /*!
  175. * Module exports.
  176. */
  177. module.exports = NativeConnection;