Skip to content

Commit

Permalink
fix(MongoClient): allow Object.prototype items as db names
Browse files Browse the repository at this point in the history
Switched the internal dbCache from a plain object to
a Map.

Fixes NODE-2060
  • Loading branch information
daprahamian committed Aug 13, 2019
1 parent affc92b commit dc6fc37
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
8 changes: 4 additions & 4 deletions lib/mongo_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ function MongoClient(url, options) {
url: url,
options: options || {},
promiseLibrary: null,
dbCache: {},
dbCache: new Map(),
sessions: [],
writeConcern: WriteConcern.fromOptions(options)
};
Expand Down Expand Up @@ -243,8 +243,8 @@ MongoClient.prototype.db = function(dbName, options) {
const finalOptions = Object.assign({}, this.s.options, options);

// Do we have the db in the cache already
if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) {
return this.s.dbCache[dbName];
if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) {
return this.s.dbCache.get(dbName);
}

// Add promiseLibrary
Expand All @@ -259,7 +259,7 @@ MongoClient.prototype.db = function(dbName, options) {
const db = new Db(dbName, this.topology, finalOptions);

// Add the db to the cache
this.s.dbCache[dbName] = db;
this.s.dbCache.set(dbName, db);
// Return the database
return db;
};
Expand Down
4 changes: 2 additions & 2 deletions lib/operations/close.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ class CloseOperation extends OperationBase {
const force = this.force;
const completeClose = err => {
client.emit('close', client);
for (const name in client.s.dbCache) {
client.s.dbCache[name].emit('close', client);
for (const item of client.s.dbCache) {
item[1].emit('close', client);
}

client.removeAllListeners('close');
Expand Down
21 changes: 21 additions & 0 deletions test/functional/mongo_client_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
var f = require('util').format;
var test = require('./shared').assert;
var setupDatabase = require('./shared').setupDatabase;
const Db = require('../../lib/db');
const expect = require('chai').expect;

describe('MongoClient', function() {
Expand Down Expand Up @@ -826,4 +827,24 @@ describe('MongoClient', function() {
});
}
});

it('should be able to access a database named "constructor"', function() {
const client = this.configuration.newClient();
let err;
return client
.connect()
.then(() => {
const db = client.db('constructor');
expect(db).to.not.be.a('function');
expect(db).to.be.an.instanceOf(Db);
})
.catch(_err => (err = _err))
.then(() => client.close())
.catch(() => {})
.then(() => {
if (err) {
throw err;
}
});
});
});

0 comments on commit dc6fc37

Please sign in to comment.