From c91d95e17e8afb9d8b3badfc658e7f20f7fb31d9 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Sat, 23 Jan 2021 17:53:35 -0500 Subject: [PATCH] fix: more quick fixes to upgrade to mongodb driver 4.x Re: #9840 --- docs/index.pug | 2 +- docs/models.pug | 2 +- docs/search.js | 2 +- docs/tutorials/ssl.md | 2 -- examples/redis-todo/db/index.js | 4 +-- index.pug | 2 +- lib/connection.js | 5 ++-- lib/index.js | 6 ----- test/collection.test.js | 4 +-- test/connection.test.js | 30 ++++++----------------- test/docs/date.test.js | 4 +-- test/es-next/cast.test.es6.js | 4 +-- test/es-next/findoneandupdate.test.es6.js | 4 +-- test/es-next/getters-setters.test.es6.js | 2 +- test/es-next/lean.test.es6.js | 4 +-- test/es-next/virtuals.test.es6.js | 2 +- test/index.test.js | 6 +---- test/typescript/connection.ts | 2 +- 18 files changed, 25 insertions(+), 62 deletions(-) diff --git a/docs/index.pug b/docs/index.pug index a1c0ecb06f..abf242b3a4 100644 --- a/docs/index.pug +++ b/docs/index.pug @@ -32,7 +32,7 @@ block content ```javascript // getting-started.js const mongoose = require('mongoose'); - mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true}); + mongoose.connect('mongodb://localhost/test'); ``` We have a pending connection to the test database running on localhost. diff --git a/docs/models.pug b/docs/models.pug index 7c4b27ff2e..d04a26938b 100644 --- a/docs/models.pug +++ b/docs/models.pug @@ -91,7 +91,7 @@ block content uses is open. Every model has an associated connection. When you use `mongoose.model()`, your model will use the default mongoose connection. ```javascript - mongoose.connect('mongodb://localhost/gettingstarted', {useNewUrlParser: true}); + mongoose.connect('mongodb://localhost/gettingstarted'); ``` :markdown If you create a custom connection, use that connection's `model()` function diff --git a/docs/search.js b/docs/search.js index c85a0feaf5..2cd05d94c7 100644 --- a/docs/search.js +++ b/docs/search.js @@ -84,7 +84,7 @@ for (const filename of files) { run().catch(error => console.error(error.stack)); async function run() { - await mongoose.connect(config.uri, { useNewUrlParser: true, dbName: 'mongoose' }); + await mongoose.connect(config.uri, { dbName: 'mongoose' }); await Content.deleteMany({}); for (const content of contents) { diff --git a/docs/tutorials/ssl.md b/docs/tutorials/ssl.md index 4595c2a29d..2747fa3c5d 100644 --- a/docs/tutorials/ssl.md +++ b/docs/tutorials/ssl.md @@ -50,8 +50,6 @@ server is not registered with an established certificate authority. The solution ```javascript await mongoose.connect('mongodb://localhost:27017/test', { - useNewUrlParser: true, - useUnifiedTopology: true, ssl: true, sslValidate: true, // For example, see https://medium.com/@rajanmaharjan/secure-your-mongodb-connections-ssl-tls-92e2addb3c89 diff --git a/examples/redis-todo/db/index.js b/examples/redis-todo/db/index.js index 84a3701f02..3305fe8a8d 100644 --- a/examples/redis-todo/db/index.js +++ b/examples/redis-todo/db/index.js @@ -2,6 +2,4 @@ const mongoose = require('mongoose'); -mongoose.connect('mongodb://localhost/redis-todo', - { useNewUrlParser: true, useCreateIndex: true } -); +mongoose.connect('mongodb://localhost/redis-todo'); diff --git a/index.pug b/index.pug index 5d6ac1b4ed..dac17537b1 100644 --- a/index.pug +++ b/index.pug @@ -121,7 +121,7 @@ html(lang='en') :markdown ```javascript const mongoose = require('mongoose'); - mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true}); + mongoose.connect('mongodb://localhost:27017/test'); const Cat = mongoose.model('Cat', { name: String }); diff --git a/lib/connection.js b/lib/connection.js index 7d2f8a1583..0466006344 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -653,11 +653,9 @@ Connection.prototype.onOpen = function() { * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic. * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. @@ -824,6 +822,9 @@ function _setClient(conn, client, options, dbName) { const db = dbName != null ? client.db(dbName) : client.db(); conn.db = db; conn.client = client; + conn.host = get(client, 's.options.hosts.0.host', void 0); + conn.port = get(client, 's.options.hosts.0.port', void 0); + conn.name = dbName != null ? dbName : get(client, 's.options.dbName', void 0); const _handleReconnect = () => { // If we aren't disconnected, we assume this reconnect is due to a diff --git a/lib/index.js b/lib/index.js index 60c603728c..a2472a1153 100644 --- a/lib/index.js +++ b/lib/index.js @@ -151,8 +151,6 @@ Mongoose.prototype.driver = require('./driver'); * - 'returnOriginal': If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](/docs/tutorials/findoneandupdate.html) for more information. * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models * - 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver. - * - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default - * - 'useUnifiedTopology': false by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model. * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. * - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas @@ -254,8 +252,6 @@ Mongoose.prototype.get = Mongoose.prototype.set; * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default. - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default. * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. @@ -314,11 +310,9 @@ Mongoose.prototype.createConnection = function(uri, options, callback) { * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic. * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. diff --git a/test/collection.test.js b/test/collection.test.js index 1afb5741b6..3cedeb681a 100644 --- a/test/collection.test.js +++ b/test/collection.test.js @@ -35,7 +35,7 @@ describe('collections:', function() { }); const uri = 'mongodb://localhost:27017/mongoose_test'; - db.openUri(process.env.MONGOOSE_TEST_URI || uri, { useNewUrlParser: true }, function(err) { + db.openUri(process.env.MONGOOSE_TEST_URI || uri, function(err) { connected = !err; finish(); }); @@ -53,7 +53,7 @@ describe('collections:', function() { }); const uri = 'mongodb://localhost:27017/mongoose_test'; - db.openUri(process.env.MONGOOSE_TEST_URI || uri, { useNewUrlParser: true }, function(err) { + db.openUri(process.env.MONGOOSE_TEST_URI || uri, function(err) { assert.ifError(err); promise.then(() => done(), done); }); diff --git a/test/connection.test.js b/test/connection.test.js index a3f3882788..eddf308465 100644 --- a/test/connection.test.js +++ b/test/connection.test.js @@ -50,8 +50,7 @@ describe('connections:', function() { it('with autoIndex (gh-5423)', function(done) { const promise = mongoose.createConnection('mongodb://localhost:27017/mongoosetest', { - autoIndex: false, - useNewUrlParser: true + autoIndex: false }).asPromise(); promise.then(function(conn) { @@ -102,8 +101,7 @@ describe('connections:', function() { it('useCreateIndex (gh-6922)', function(done) { const conn = mongoose.createConnection('mongodb://localhost:27017/mongoosetest', { - useCreateIndex: true, - useNewUrlParser: true + useCreateIndex: true }); const M = conn.model('Test', new Schema({ @@ -125,15 +123,14 @@ describe('connections:', function() { it('throws helpful error with undefined uri (gh-6763)', function() { assert.throws(function() { - mongoose.createConnection(void 0, { useNewUrlParser: true }); + mongoose.createConnection(void 0); }, /string.*createConnection/); }); it('resolving with q (gh-5714)', function(done) { const bootMongo = Q.defer(); - const conn = mongoose.createConnection('mongodb://localhost:27017/mongoosetest', - { useNewUrlParser: true }); + const conn = mongoose.createConnection('mongodb://localhost:27017/mongoosetest'); conn.on('connected', function() { bootMongo.resolve(this); @@ -146,10 +143,8 @@ describe('connections:', function() { }); it('connection plugins (gh-7378)', function() { - const conn1 = mongoose.createConnection('mongodb://localhost:27017/mongoosetest', - { useNewUrlParser: true }); - const conn2 = mongoose.createConnection('mongodb://localhost:27017/mongoosetest', - { useNewUrlParser: true }); + const conn1 = mongoose.createConnection('mongodb://localhost:27017/mongoosetest'); + const conn2 = mongoose.createConnection('mongodb://localhost:27017/mongoosetest'); const called = []; conn1.plugin(schema => called.push(schema)); @@ -230,17 +225,6 @@ describe('connections:', function() { db.close(done); }); - it('should accept unix domain sockets', function() { - const host = encodeURIComponent('/tmp/mongodb-27017.sock'); - const db = mongoose.createConnection(`mongodb://aaron:psw@${host}/fake`); - db.asPromise().catch(() => {}); - assert.equal(db.name, 'fake'); - assert.equal(db.host, '/tmp/mongodb-27017.sock'); - assert.equal(db.pass, 'psw'); - assert.equal(db.user, 'aaron'); - db.close(); - }); - describe('errors', function() { it('.catch() means error does not get thrown (gh-5229)', function(done) { const db = mongoose.createConnection(); @@ -286,7 +270,7 @@ describe('connections:', function() { describe('connect callbacks', function() { it('should return an error if malformed uri passed', function(done) { - const db = mongoose.createConnection('mongodb:///fake', { useNewUrlParser: true }, function(err) { + const db = mongoose.createConnection('mongodb:///fake', {}, function(err) { assert.equal(err.name, 'MongoParseError'); done(); }); diff --git a/test/docs/date.test.js b/test/docs/date.test.js index 7dad6f7147..e1536dc82e 100644 --- a/test/docs/date.test.js +++ b/test/docs/date.test.js @@ -18,9 +18,7 @@ describe('Date Tutorial', function() { }); User = mongoose.model('User', userSchema); - return mongoose.connect('mongodb://localhost:27017/mongoose', { - useNewUrlParser: true - }); + return mongoose.connect('mongodb://localhost:27017/mongoose'); }); it('Example 1.2: casts strings to dates', function() { diff --git a/test/es-next/cast.test.es6.js b/test/es-next/cast.test.es6.js index 92c76b6d05..efd58eac1e 100644 --- a/test/es-next/cast.test.es6.js +++ b/test/es-next/cast.test.es6.js @@ -13,9 +13,7 @@ describe('Cast Tutorial', function() { const schema = new mongoose.Schema({ name: String, age: Number }); Character = mongoose.model('Character', schema); - await mongoose.connect('mongodb://localhost:27017/mongoose', { - useNewUrlParser: true - }); + await mongoose.connect('mongodb://localhost:27017/mongoose'); await Character.deleteMany({}); await Character.create({ diff --git a/test/es-next/findoneandupdate.test.es6.js b/test/es-next/findoneandupdate.test.es6.js index c8364ac3fe..19e5626549 100644 --- a/test/es-next/findoneandupdate.test.es6.js +++ b/test/es-next/findoneandupdate.test.es6.js @@ -10,9 +10,7 @@ describe('Tutorial: findOneAndUpdate()', function() { let Character; before(async function() { - await mongoose.connect('mongodb://localhost:27017/mongoose', { - useNewUrlParser: true - }); + await mongoose.connect('mongodb://localhost:27017/mongoose'); await mongoose.connection.dropDatabase(); }); diff --git a/test/es-next/getters-setters.test.es6.js b/test/es-next/getters-setters.test.es6.js index 2d1a8f4452..fca73b323c 100644 --- a/test/es-next/getters-setters.test.es6.js +++ b/test/es-next/getters-setters.test.es6.js @@ -10,7 +10,7 @@ const Schema = mongoose.Schema; describe('getters/setters', function() { before(async function() { - await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }); + await mongoose.connect('mongodb://localhost:27017/test'); }); beforeEach(function() { diff --git a/test/es-next/lean.test.es6.js b/test/es-next/lean.test.es6.js index f9153e8bca..2c09e166ec 100644 --- a/test/es-next/lean.test.es6.js +++ b/test/es-next/lean.test.es6.js @@ -13,9 +13,7 @@ describe('Lean Tutorial', function() { const schema = new mongoose.Schema({ name: String }); MyModel = mongoose.model('Test1', schema); - return mongoose.connect('mongodb://localhost:27017/mongoose', { - useNewUrlParser: true - }); + return mongoose.connect('mongodb://localhost:27017/mongoose'); }); beforeEach(function() { diff --git a/test/es-next/virtuals.test.es6.js b/test/es-next/virtuals.test.es6.js index 03bc01b72c..a39b3e999b 100644 --- a/test/es-next/virtuals.test.es6.js +++ b/test/es-next/virtuals.test.es6.js @@ -10,7 +10,7 @@ const Schema = mongoose.Schema; describe('Virtuals', function() { before(async function() { - await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }); + await mongoose.connect('mongodb://localhost:27017/test'); }); beforeEach(function() { diff --git a/test/index.test.js b/test/index.test.js index 322fa4df39..fdbc5dbaf6 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -15,9 +15,7 @@ const Schema = mongoose.Schema; const uri = 'mongodb://localhost:27017/mongoose_test'; -const options = { - useNewUrlParser: true -}; +const options = {}; describe('mongoose module:', function() { describe('default connection works', function() { @@ -101,11 +99,9 @@ describe('mongoose module:', function() { const mongoose = new Mongoose(); mongoose.set('runValidators', 'b'); - mongoose.set('useNewUrlParser', 'c'); assert.equal(mongoose.get('runValidators'), 'b'); assert.equal(mongoose.set('runValidators'), 'b'); - assert.equal(mongoose.get('useNewUrlParser'), 'c'); }); it('allows `const { model } = mongoose` (gh-3768)', function() { diff --git a/test/typescript/connection.ts b/test/typescript/connection.ts index eb3b909523..5f24b49a03 100644 --- a/test/typescript/connection.ts +++ b/test/typescript/connection.ts @@ -6,7 +6,7 @@ conn.model('Test', new Schema({ name: { type: String } })); conn.openUri('mongodb://localhost:27017/test').then(() => console.log('Connected!')); -createConnection('mongodb://localhost:27017/test', { useNewUrlParser: true }).then((conn: Connection) => { +createConnection('mongodb://localhost:27017/test').then((conn: Connection) => { conn.host; });