Skip to content

Commit

Permalink
fix: clean up remaining test failures with MongoDB driver 4.0 beta
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jan 30, 2021
1 parent c1595d0 commit 26f25c1
Show file tree
Hide file tree
Showing 13 changed files with 33 additions and 334 deletions.
15 changes: 13 additions & 2 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,8 @@ Connection.prototype.onOpen = function() {
* @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
* @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 {Number} [options.maxPoolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that 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 {Number} [options.minPoolSize=1] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that 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 {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.
Expand Down Expand Up @@ -776,7 +777,13 @@ Connection.prototype.openUri = function(uri, options, callback) {
}

const promise = new Promise((resolve, reject) => {
const client = new mongodb.MongoClient(uri, options);
let client;
try {
client = new mongodb.MongoClient(uri, options);
} catch (error) {
_this.readyState = STATES.disconnected;
return reject(error);
}
_this.client = client;
client.connect((error) => {
if (error) {
Expand Down Expand Up @@ -991,6 +998,10 @@ Connection.prototype.onClose = function(force) {
}

this.emit('close', force);

for (const db of this.otherDbs) {
db.close(force);
}
};

/**
Expand Down
3 changes: 2 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,8 @@ Mongoose.prototype.get = Mongoose.prototype.set;
* @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.
* @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
* @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 {Number} [options.maxPoolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that 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 {Number} [options.minPoolSize=1] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that 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 {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
* @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
* @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
Expand Down
91 changes: 2 additions & 89 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,8 @@ Model.prototype.$__save = function(options, callback) {
if (result) {
if (Array.isArray(result)) {
numAffected = result.length;
} else if (result.modifiedCount != null) {
numAffected = result.modifiedCount;
} else if (result.matchedCount != null) {
numAffected = result.matchedCount;
} else {
numAffected = result;
}
Expand Down Expand Up @@ -4052,93 +4052,6 @@ Model.validate = function validate(obj, pathsToValidate, context, callback) {
});
};

/**
* Implements `$geoSearch` functionality for Mongoose
*
* This function does not trigger any middleware
*
* ####Example:
*
* const options = { near: [10, 10], maxDistance: 5 };
* Locations.geoSearch({ type : "house" }, options, function(err, res) {
* console.log(res);
* });
*
* ####Options:
* - `near` {Array} x,y point to search for
* - `maxDistance` {Number} the maximum distance from the point near that a result can be
* - `limit` {Number} The maximum number of results to return
* - `lean` {Object|Boolean} return the raw object instead of the Mongoose Model
*
* @param {Object} conditions an object that specifies the match condition (required)
* @param {Object} options for the geoSearch, some (near, maxDistance) are required
* @param {Object|Boolean} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
* @param {Function} [callback] optional callback
* @return {Promise}
* @see http://docs.mongodb.org/manual/reference/command/geoSearch/
* @see http://docs.mongodb.org/manual/core/geohaystack/
* @api public
*/

Model.geoSearch = function(conditions, options, callback) {
_checkContext(this, 'geoSearch');

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

callback = this.$handleCallbackError(callback);

return this.db.base._promiseOrCallback(callback, cb => {
cb = this.$wrapCallback(cb);
let error;
if (conditions === undefined || !utils.isObject(conditions)) {
error = new MongooseError('Must pass conditions to geoSearch');
} else if (!options.near) {
error = new MongooseError('Must specify the near option in geoSearch');
} else if (!Array.isArray(options.near)) {
error = new MongooseError('near option must be an array [x, y]');
}

if (error) {
return cb(error);
}

// send the conditions in the options object
options.search = conditions;

this.collection.geoHaystackSearch(options.near[0], options.near[1], options, (err, res) => {
if (err) {
return cb(err);
}

let count = res.results.length;
if (options.lean || count === 0) {
return cb(null, res.results);
}

const errSeen = false;

function init(err) {
if (err && !errSeen) {
return cb(err);
}

if (!--count && !errSeen) {
cb(null, res.results);
}
}

for (let i = 0; i < res.results.length; ++i) {
const temp = res.results[i];
res.results[i] = new this();
res.results[i].init(temp, {}, init);
}
});
}, this.events);
};

/**
* Populates document references.
*
Expand Down
2 changes: 1 addition & 1 deletion test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ describe('connections:', function() {
yield db.openUri('fail connection');
} catch (err) {
assert.ok(err);
assert.equal(err.name, 'MongoParseError');
threw = true;
}

Expand Down Expand Up @@ -511,7 +512,6 @@ describe('connections:', function() {
const db2 = db.useDb('mongoose2');

assert.equal('mongoose2', db2.name);
assert.equal('mongoose1', db.name);

assert.equal(db2.port, db.port);
assert.equal(db2.replica, db.replica);
Expand Down
3 changes: 2 additions & 1 deletion test/docs/validation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ describe('validation docs', function() {

before(function() {
db = mongoose.createConnection('mongodb://localhost:27017/mongoose_test', {
poolSize: 1
minPoolSize: 1,
maxPoolSize: 1
});
});

Expand Down
4 changes: 2 additions & 2 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2073,7 +2073,7 @@ describe('document', function() {
}
catch (err) {
assert.equal(err instanceof DocumentNotFoundError, true);
assert.equal(err.message, `No document found for query "{ _id: ${person._id} }" on model "Person"`);
assert.equal(err.message, `No document found for query "{ _id: ObjectId("${person._id}") }" on model "Person"`);
threw = true;
}

Expand All @@ -2098,7 +2098,7 @@ describe('document', function() {
}
catch (err) {
assert.equal(err instanceof DocumentNotFoundError, true);
assert.equal(err.message, `No document found for query "{ _id: ${person._id} }" on model "Person"`);
assert.equal(err.message, `No document found for query "{ _id: ObjectId("${person._id}") }" on model "Person"`);
threw = true;
}

Expand Down
8 changes: 4 additions & 4 deletions test/es-next/lean.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ describe('Lean Tutorial', function() {
// To enable the `lean` option for a query, use the `lean()` function.
const leanDoc = await MyModel.findOne().lean();

sizeof(normalDoc); // >= 1000
sizeof(leanDoc); // 86, 10x smaller!
sizeof(normalDoc); // approximately 1000
sizeof(leanDoc); // 36, more than 10x smaller!

// In case you were wondering, the JSON form of a Mongoose doc is the same
// as the POJO. This additional memory only affects how much memory your
// Node.js process uses, not how much data is sent over the network.
JSON.stringify(normalDoc).length === JSON.stringify(leanDoc.length); // true
// acquit:ignore:start
assert.ok(sizeof(normalDoc) >= 1000);
assert.equal(sizeof(leanDoc), 86);
assert.ok(sizeof(normalDoc) >= 750 && sizeof(normalDoc) <= 1250, sizeof(normalDoc));
assert.equal(sizeof(leanDoc), 36);
assert.equal(JSON.stringify(normalDoc).length, JSON.stringify(leanDoc).length);
// acquit:ignore:end
});
Expand Down
3 changes: 2 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,8 @@ describe('mongoose module:', function() {

it('connect with url doesnt cause unhandled rejection (gh-6997)', function(done) {
const m = new mongoose.Mongoose;
m.connect('mongodb://doesnotexist:27009/test', options, function(error) {
const _options = Object.assign({}, options, { serverSelectionTimeoutMS: 100 });
m.connect('mongodb://doesnotexist:27009/test', _options, function(error) {
assert.ok(error);
done();
});
Expand Down
Loading

0 comments on commit 26f25c1

Please sign in to comment.