Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add openUri() and useMongooseUri option, deprecate open() and openSet() #5355

Merged
merged 7 commits into from
Jun 24, 2017
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 25 additions & 3 deletions docs/connections.jade
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ extends layout
block content
h2 Connections
:markdown
We may connect to MongoDB by utilizing the `mongoose.connect()` method.
You can connect to MongoDB with the `mongoose.connect()` method.

:js
mongoose.connect('mongodb://localhost/myapp');

:markdown
This is the minimum needed to connect the `myapp` database running locally on the default port (27017). If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.
This is the minimum needed to connect the `myapp` database running locally
on the default port (27017). If the local connection fails then try using
127.0.0.1 instead of localhost. Sometimes issues may arise when the local
hostname has been changed.

We may also specify several more parameters in the `uri` depending on your environment:
You can also specify several more parameters in the `uri`:

:js
mongoose.connect('mongodb://username:password@host:port/database?options...');
Expand Down Expand Up @@ -189,6 +192,25 @@ block content
// passing the option in the URI works with single or replica sets
var uri = 'mongodb://localhost/test?poolSize=4';
mongoose.createConnection(uri);

h3#use-mongoose-uri
:markdown
Mongoose's default connection logic is deprecated as of 4.11.0. Please opt
in to the new connection logic using the `useMongooseUri` option, but
make sure you test your connections first if you're upgrading an existing
codebase!
:js
// Using `mongoose.connect`...
var promise = mongoose.connect('mongodb://localhost/myapp', { useMongooseUri: true, /* other options */ });
// Or `createConnection`
var promise = mongoose.createConnection('mongodb://localhost/myapp', { useMongooseUri: true, /* other options */ });
// Or, if you already have a connection
connection.openUri('mongodb://localhost/myapp', { /* options */ });
:markdown
This deprecation is because the [MongoDB driver](https://www.npmjs.com/package/mongodb)
has deprecated an API that is critical to mongoose's connection logic to
support MongoDB 3.6, see [this github issue](https://github.com/Automattic/mongoose/issues/5304)
for more details.

h3#next Next Up
:markdown
Expand Down
56 changes: 52 additions & 4 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ var STATES = require('./connectionstate');
var MongooseError = require('./error');
var muri = require('muri');
var PromiseProvider = require('./promise_provider');
var mongodb = require('mongodb');
var util = require('util');

/*!
* Protocol prefix regexp.
Expand Down Expand Up @@ -298,7 +300,7 @@ Connection.prototype._handleOpenArgs = function(host, database, port, options, c
* @api public
*/

Connection.prototype.open = function() {
Connection.prototype.open = util.deprecate(function() {
var Promise = PromiseProvider.get();
var callback;

Expand Down Expand Up @@ -337,7 +339,7 @@ Connection.prototype.open = function() {
};

return promise;
};
}, '`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongooseUri` option if using `connect()` or `createConnection()`');

/*!
* ignore
Expand Down Expand Up @@ -561,7 +563,7 @@ Connection.prototype._openSetWithoutPromise = function(uris, database, options,
* @api public
*/

Connection.prototype.openSet = function(uris, database, options, callback) {
Connection.prototype.openSet = util.deprecate(function(uris, database, options, callback) {
var Promise = PromiseProvider.get();

try {
Expand Down Expand Up @@ -598,7 +600,7 @@ Connection.prototype.openSet = function(uris, database, options, callback) {
};

return promise;
};
}, '`openSet()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongooseUri` option if using `connect()` or `createConnection()`');

/**
* error
Expand Down Expand Up @@ -693,6 +695,52 @@ Connection.prototype.onOpen = function(callback) {
}
};

/**
* Opens the connection with a URI using `MongoClient.connect()`.
*
* @param {String} uri The URI to connect with.
* @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect
* @param {Function} [callback]
* @returns {Connection} this
* @api private
*/

Connection.prototype.openUri = function(uri, options, callback) {
this.readyState = STATES.connecting;
this._closeCalled = false;

if (typeof options === 'function') {
callback = options;
options = null;
}

var Promise = PromiseProvider.get();
var _this = this;

if (options && options.useMongooseUri) {
options = utils.clone(options, { retainKeyOrder: true });
delete options.useMongooseUri;
}

return new Promise.ES6(function(resolve, reject) {
mongodb.MongoClient.connect(uri, options, function(error, db) {
if (error) {
_this.readyState = STATES.disconnected;
if (_this.listeners('error').length) {
_this.emit('error', error);
}
return reject(error);
}
_this.db = db;
_this.readyState = STATES.connected;

callback && callback(null, _this);
resolve(_this);
_this.emit('open');
});
});
};

/**
* Closes the connection
*
Expand Down
37 changes: 25 additions & 12 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
* Module dependencies.
*/

var Schema = require('./schema'),
SchemaType = require('./schematype'),
VirtualType = require('./virtualtype'),
STATES = require('./connectionstate'),
Types = require('./types'),
Query = require('./query'),
Model = require('./model'),
Document = require('./document'),
utils = require('./utils'),
format = utils.toCollectionName,
pkg = require('../package.json');
var Schema = require('./schema');
var SchemaType = require('./schematype');
var VirtualType = require('./virtualtype');
var STATES = require('./connectionstate');
var Types = require('./types');
var Query = require('./query');
var Model = require('./model');
var Document = require('./document');
var utils = require('./utils');
var format = utils.toCollectionName;
var pkg = require('../package.json');

var querystring = require('querystring');
var saveSubdocs = require('./plugins/saveSubdocs');
Expand Down Expand Up @@ -185,9 +185,10 @@ var checkReplicaSetInUri = function(uri) {
* @param {Object} [options] options to pass to the driver
* @param {Object} [options.config] mongoose-specific options
* @param {Boolean} [options.config.autoIndex] set to false to disable automatic index creation for all models associated with this connection.
* @param {Boolean} [options.useMongooseUri] false by default, set to true to use new mongoose connection logic
* @see Connection#open #connection_Connection-open
* @see Connection#openSet #connection_Connection-openSet
* @return {Connection} the created Connection object
* @return {Connection|Promise} the created Connection object, or promise that resolves to the connection if `useMongooseUri` option specified.
* @api public
*/

Expand All @@ -196,6 +197,11 @@ Mongoose.prototype.createConnection = function(uri, options) {
this.connections.push(conn);

var rsOption = options && (options.replset || options.replSet);

if (options && options.useMongooseUri) {
return conn.openUri(uri, options);
}

if (arguments.length) {
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
conn._openSetWithoutPromise.apply(conn, arguments);
Expand Down Expand Up @@ -244,6 +250,7 @@ Mongoose.prototype.createConnection.$hasSideEffects = true;
*
* @param {String} uri(s)
* @param {Object} [options]
* @param {Boolean} [options.useMongooseUri] false by default, set to true to use new mongoose connection logic
* @param {Function} [callback]
* @see Mongoose#createConnection #index_Mongoose-createConnection
* @api public
Expand All @@ -252,6 +259,12 @@ Mongoose.prototype.createConnection.$hasSideEffects = true;

Mongoose.prototype.connect = function() {
var conn = this.connection;
if ((arguments.length === 2 || arguments.length === 3) &&
typeof arguments[0] === 'string' &&
typeof arguments[1] === 'object' &&
arguments[1].useMongooseUri === true) {
return conn.openUri(arguments[0], arguments[1], arguments[2]);
}
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
return new MongooseThenable(this, conn.openSet.apply(conn, arguments));
}
Expand Down
24 changes: 24 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,30 @@ var muri = require('muri');
*/

describe('connections:', function() {
describe('useMongooseUri/openUri (gh-5304)', function() {
it('with mongoose.connect()', function(done) {
var promise = mongoose.connect('mongodb://localhost:27017/mongoosetest', { useMongooseUri: true });
assert.equal(promise.constructor.name, 'Promise');

promise.then(function(conn) {
assert.equal(conn.constructor.name, 'NativeConnection');

return mongoose.disconnect().then(function() { done(); });
}).catch(done);
});

it('with mongoose.createConnection()', function(done) {
var promise = mongoose.createConnection('mongodb://localhost:27017/mongoosetest', { useMongooseUri: true });
assert.equal(promise.constructor.name, 'Promise');

promise.then(function(conn) {
assert.equal(conn.constructor.name, 'NativeConnection');

return mongoose.disconnect().then(function() { done(); });
}).catch(done);
});
});

it('should allow closing a closed connection', function(done) {
var db = mongoose.createConnection();

Expand Down