connection.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseConnection = require('../../connection');
  6. const STATES = require('../../connectionstate');
  7. const immediate = require('../../helpers/immediate');
  8. const setTimeout = require('../../helpers/timers').setTimeout;
  9. /**
  10. * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
  11. *
  12. * @inherits Connection
  13. * @api private
  14. */
  15. function NativeConnection() {
  16. MongooseConnection.apply(this, arguments);
  17. this._listening = false;
  18. }
  19. /**
  20. * Expose the possible connection states.
  21. * @api public
  22. */
  23. NativeConnection.STATES = STATES;
  24. /*!
  25. * Inherits from Connection.
  26. */
  27. NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
  28. /**
  29. * Switches to a different database using the same connection pool.
  30. *
  31. * Returns a new connection object, with the new db. If you set the `useCache`
  32. * option, `useDb()` will cache connections by `name`.
  33. *
  34. * **Note:** Calling `close()` on a `useDb()` connection will close the base connection as well.
  35. *
  36. * @param {String} name The database name
  37. * @param {Object} [options]
  38. * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
  39. * @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.
  40. * @return {Connection} New Connection Object
  41. * @api public
  42. */
  43. NativeConnection.prototype.useDb = function(name, options) {
  44. // Return immediately if cached
  45. options = options || {};
  46. if (options.useCache && this.relatedDbs[name]) {
  47. return this.relatedDbs[name];
  48. }
  49. // we have to manually copy all of the attributes...
  50. const newConn = new this.constructor();
  51. newConn.name = name;
  52. newConn.base = this.base;
  53. newConn.collections = {};
  54. newConn.models = {};
  55. newConn.replica = this.replica;
  56. newConn.config = Object.assign({}, this.config, newConn.config);
  57. newConn.name = this.name;
  58. newConn.options = this.options;
  59. newConn._readyState = this._readyState;
  60. newConn._closeCalled = this._closeCalled;
  61. newConn._hasOpened = this._hasOpened;
  62. newConn._listening = false;
  63. newConn._parent = this;
  64. newConn.host = this.host;
  65. newConn.port = this.port;
  66. newConn.user = this.user;
  67. newConn.pass = this.pass;
  68. // First, when we create another db object, we are not guaranteed to have a
  69. // db object to work with. So, in the case where we have a db object and it
  70. // is connected, we can just proceed with setting everything up. However, if
  71. // we do not have a db or the state is not connected, then we need to wait on
  72. // the 'open' event of the connection before doing the rest of the setup
  73. // the 'connected' event is the first time we'll have access to the db object
  74. const _this = this;
  75. newConn.client = _this.client;
  76. if (this.db && this._readyState === STATES.connected) {
  77. wireup();
  78. } else {
  79. this.once('connected', wireup);
  80. }
  81. function wireup() {
  82. newConn.client = _this.client;
  83. const _opts = {};
  84. if (options.hasOwnProperty('noListener')) {
  85. _opts.noListener = options.noListener;
  86. }
  87. newConn.db = _this.client.db(name, _opts);
  88. newConn.onOpen();
  89. }
  90. newConn.name = name;
  91. // push onto the otherDbs stack, this is used when state changes
  92. if (options.noListener !== true) {
  93. this.otherDbs.push(newConn);
  94. }
  95. newConn.otherDbs.push(this);
  96. // push onto the relatedDbs cache, this is used when state changes
  97. if (options && options.useCache) {
  98. this.relatedDbs[newConn.name] = newConn;
  99. newConn.relatedDbs = this.relatedDbs;
  100. }
  101. return newConn;
  102. };
  103. /**
  104. * Closes the connection
  105. *
  106. * @param {Boolean} [force]
  107. * @param {Function} [fn]
  108. * @return {Connection} this
  109. * @api private
  110. */
  111. NativeConnection.prototype.doClose = function(force, fn) {
  112. if (this.client == null) {
  113. immediate(() => fn());
  114. return this;
  115. }
  116. this.client.close(force, (err, res) => {
  117. // Defer because the driver will wait at least 1ms before finishing closing
  118. // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030.
  119. // If there's queued operations, you may still get some background work
  120. // after the callback is called.
  121. setTimeout(() => fn(err, res), 1);
  122. });
  123. return this;
  124. };
  125. /*!
  126. * Module exports.
  127. */
  128. module.exports = NativeConnection;