Skip to content

Commit dc6fc37

Browse files
committed
fix(MongoClient): allow Object.prototype items as db names
Switched the internal dbCache from a plain object to a Map. Fixes NODE-2060
1 parent affc92b commit dc6fc37

File tree

3 files changed

+27
-6
lines changed

3 files changed

+27
-6
lines changed

lib/mongo_client.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ function MongoClient(url, options) {
148148
url: url,
149149
options: options || {},
150150
promiseLibrary: null,
151-
dbCache: {},
151+
dbCache: new Map(),
152152
sessions: [],
153153
writeConcern: WriteConcern.fromOptions(options)
154154
};
@@ -243,8 +243,8 @@ MongoClient.prototype.db = function(dbName, options) {
243243
const finalOptions = Object.assign({}, this.s.options, options);
244244

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

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

261261
// Add the db to the cache
262-
this.s.dbCache[dbName] = db;
262+
this.s.dbCache.set(dbName, db);
263263
// Return the database
264264
return db;
265265
};

lib/operations/close.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ class CloseOperation extends OperationBase {
1616
const force = this.force;
1717
const completeClose = err => {
1818
client.emit('close', client);
19-
for (const name in client.s.dbCache) {
20-
client.s.dbCache[name].emit('close', client);
19+
for (const item of client.s.dbCache) {
20+
item[1].emit('close', client);
2121
}
2222

2323
client.removeAllListeners('close');

test/functional/mongo_client_tests.js

+21
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
var f = require('util').format;
44
var test = require('./shared').assert;
55
var setupDatabase = require('./shared').setupDatabase;
6+
const Db = require('../../lib/db');
67
const expect = require('chai').expect;
78

89
describe('MongoClient', function() {
@@ -826,4 +827,24 @@ describe('MongoClient', function() {
826827
});
827828
}
828829
});
830+
831+
it('should be able to access a database named "constructor"', function() {
832+
const client = this.configuration.newClient();
833+
let err;
834+
return client
835+
.connect()
836+
.then(() => {
837+
const db = client.db('constructor');
838+
expect(db).to.not.be.a('function');
839+
expect(db).to.be.an.instanceOf(Db);
840+
})
841+
.catch(_err => (err = _err))
842+
.then(() => client.close())
843+
.catch(() => {})
844+
.then(() => {
845+
if (err) {
846+
throw err;
847+
}
848+
});
849+
});
829850
});

0 commit comments

Comments
 (0)