diff --git a/lib/mongo_client.js b/lib/mongo_client.js index 8aa7fe6307..b1a3bedc2a 100644 --- a/lib/mongo_client.js +++ b/lib/mongo_client.js @@ -201,8 +201,9 @@ MongoClient.prototype.close = function(force, callback) { if (typeof force === 'function') (callback = force), (force = false); // Close the topology connection - this.topology.close(force); - + if (this.topology) { + this.topology.close(force); + } // Emit close event this.emit('close', this); diff --git a/lib/operations/mongo_client_ops.js b/lib/operations/mongo_client_ops.js index 3bf7552ff7..7131dddf1f 100644 --- a/lib/operations/mongo_client_ops.js +++ b/lib/operations/mongo_client_ops.js @@ -334,16 +334,21 @@ function createServer(mongoClient, options, callback) { // Propagate the events to the client const collectedEvents = collectEvents(mongoClient, servers[0]); + const server = servers[0]; + // Connect to topology - servers[0].connect(options, (err, topology) => { - if (err) return callback(err); + server.connect(options, (err, topology) => { + if (err) { + server.close(true); + return callback(err); + } // Clear out all the collected event listeners - clearAllEvents(servers[0]); + clearAllEvents(server); // Relay all the events - relayEvents(mongoClient, servers[0]); + relayEvents(mongoClient, server); // Add listeners - addListeners(mongoClient, servers[0]); + addListeners(mongoClient, server); // Check if we are really speaking to a mongos const ismaster = topology.lastIsMaster(); @@ -388,7 +393,10 @@ function createTopology(mongoClient, topologyType, options, callback) { // Open the connection topology.connect(options, (err, topology) => { - if (err) return callback(err); + if (err) { + topology.close(true); + return callback(err); + } assignTopology(mongoClient, topology); callback(null, topology);