Skip to content

Commit

Permalink
fix: more quick fixes to upgrade to mongodb driver 4.x
Browse files Browse the repository at this point in the history
Re: #9840
  • Loading branch information
vkarpov15 committed Jan 23, 2021
1 parent 442d754 commit c91d95e
Show file tree
Hide file tree
Showing 18 changed files with 25 additions and 62 deletions.
2 changes: 1 addition & 1 deletion docs/index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/models.pug
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 0 additions & 2 deletions docs/tutorials/ssl.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions examples/redis-todo/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/redis-todo',
{ useNewUrlParser: true, useCreateIndex: true }
);
mongoose.connect('mongodb://localhost/redis-todo');
2 changes: 1 addition & 1 deletion index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
5 changes: 3 additions & 2 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
6 changes: 0 additions & 6 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions test/collection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand All @@ -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);
});
Expand Down
30 changes: 7 additions & 23 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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({
Expand All @@ -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);
Expand All @@ -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));
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
});
Expand Down
4 changes: 1 addition & 3 deletions test/docs/date.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
4 changes: 1 addition & 3 deletions test/es-next/cast.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
4 changes: 1 addition & 3 deletions test/es-next/findoneandupdate.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down
2 changes: 1 addition & 1 deletion test/es-next/getters-setters.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
4 changes: 1 addition & 3 deletions test/es-next/lean.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion test/es-next/virtuals.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
6 changes: 1 addition & 5 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion test/typescript/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});

Expand Down

0 comments on commit c91d95e

Please sign in to comment.