Skip to content

Commit d4b5ba5

Browse files
committed
feat: upgrade mongodb driver to version 5.x
Signed-off-by: Matteo Padovano <[email protected]>
1 parent fe4a2f9 commit d4b5ba5

File tree

4 files changed

+391
-329
lines changed

4 files changed

+391
-329
lines changed

lib/mongodb.js

+208-89
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,8 @@ function MongoDB(settings, dataSource) {
197197
this.settings.enableOptimizedfindOrCreate === true ||
198198
this.settings.enableOptimizedFindOrCreate === true
199199
) {
200-
debug('Optimized findOrCreate is enabled by default, and the enableOptimizedFindOrCreate setting is ignored since v7.0.0.')
200+
debug('Optimized findOrCreate is enabled by default, and the enableOptimizedFindOrCreate setting ' +
201+
'is ignored since v7.0.0.');
201202
}
202203

203204
if (this.settings.enableGeoIndexing === true) {
@@ -230,82 +231,189 @@ MongoDB.prototype.connect = function(callback) {
230231
});
231232
});
232233
} else {
233-
// See https://github.com/mongodb/node-mongodb-native/blob/3.7/lib/mongo_client.js#L94
234+
// See https://www.mongodb.com/docs/manual/reference/connection-string
234235
const validOptionNames = [
235-
'poolSize',
236-
'ssl',
237-
'sslValidate',
238-
'sslCA',
239-
'sslCert',
240-
'sslKey',
241-
'sslPass',
242-
'sslCRL',
236+
'replicaSet',
237+
/** Enables or disables TLS/SSL for the connection. */
243238
'tls',
239+
/** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
240+
'ssl',
241+
/**
242+
* Specifies the location of a local TLS Certificate
243+
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
244+
*/
245+
'tlsCertificateFile',
246+
/** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */
244247
'tlsCertificateKeyFile',
248+
/** Specifies the password to de-crypt the tlsCertificateKeyFile. */
245249
'tlsCertificateKeyFilePassword',
250+
/** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */
251+
'tlsCAFile',
252+
/** Bypasses validation of the certificates presented by the mongod/mongos instance */
246253
'tlsAllowInvalidCertificates',
254+
/** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
247255
'tlsAllowInvalidHostnames',
256+
/** Disables various certificate validations. */
248257
'tlsInsecure',
249-
'tlsCAFile',
250-
'autoReconnect',
251-
'noDelay',
252-
'keepAlive',
253-
'keepAliveInitialDelay',
258+
/** The time in milliseconds to attempt a connection before timing out. */
254259
'connectTimeoutMS',
255-
'serverSelectionTimeoutMS',
256-
'family',
260+
/** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
257261
'socketTimeoutMS',
258-
'reconnectTries',
259-
'reconnectInterval',
260-
'ha',
261-
'haInterval',
262-
'replicaSet',
263-
'secondaryAcceptableLatencyMS',
264-
'acceptableLatencyMS',
265-
'connectWithNoPrimary',
266-
'authSource',
267-
'forceServerObjectId',
268-
'serializeFunctions',
269-
'ignoreUndefined',
270-
'raw',
271-
'bufferMaxEntries',
272-
'readPreference',
273-
'pkFactory',
274-
'promiseLibrary',
262+
/** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
263+
'compressors',
264+
/** An integer that specifies the compression level if using zlib for network compression. */
265+
'zlibCompressionLevel',
266+
/** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
267+
'srvMaxHosts',
268+
/**
269+
* Modifies the srv URI to look like:
270+
*
271+
* `_{srvServiceName}._tcp.{hostname}.{domainname}`
272+
*
273+
* Querying this DNS URI is expected to respond with SRV records
274+
*/
275+
'srvServiceName',
276+
/** The maximum number of connections in the connection pool. */
277+
'maxPoolSize',
278+
/** The minimum number of connections in the connection pool. */
279+
'minPoolSize',
280+
/** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
281+
'maxConnecting',
282+
/** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */
283+
'maxIdleTimeMS',
284+
/** The maximum time in milliseconds that a thread can wait for a connection to become available. */
285+
'waitQueueTimeoutMS',
286+
/** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
275287
'readConcern',
288+
/** The level of isolation */
289+
'readConcernLevel',
290+
/** Specifies the read preferences for this connection */
291+
'readPreference',
292+
/** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
276293
'maxStalenessSeconds',
277-
'loggerLevel',
278-
'logger',
279-
'promoteValues',
280-
'promoteBuffers',
281-
'promoteLongs',
282-
'domainsEnabled',
283-
'checkServerIdentity',
284-
'validateOptions',
285-
'appname',
294+
/** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */
295+
'readPreferenceTags',
296+
/** The auth settings for when connection to server. */
286297
'auth',
298+
/** Specify the database name associated with the user’s credentials. */
299+
'authSource',
300+
/** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
287301
'authMechanism',
288-
'compression',
289-
'readPreferenceTags',
290-
'numberOfRetries',
291-
'auto_reconnect',
292-
'minSize',
293-
'useNewUrlParser',
294-
'useUnifiedTopology',
295-
'writeConcern',
296-
// Ignored options
297-
'native_parser',
298-
// Legacy options
299-
'server',
300-
'replset',
301-
'replSet',
302-
'mongos',
303-
'db',
302+
/** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
303+
'authMechanismProperties',
304+
/** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
305+
'localThresholdMS',
306+
/** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
307+
'serverSelectionTimeoutMS',
308+
/** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */
309+
'heartbeatFrequencyMS',
310+
/** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */
311+
'minHeartbeatFrequencyMS',
312+
/** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */
313+
'appName',
314+
/** Enables retryable reads. */
315+
'retryReads',
316+
/** Enable retryable writes. */
317+
'retryWrites',
318+
/** Allow a driver to force a Single topology type with a connection string containing one host */
319+
'directConnection',
320+
/** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
321+
'loadBalanced',
322+
/**
323+
* The write concern w value
324+
* @deprecated Please use the `writeConcern` option instead
325+
*/
304326
'w',
305-
'wtimeout',
306-
'j',
327+
/**
328+
* The write concern timeout
329+
* @deprecated Please use the `writeConcern` option instead
330+
*/
331+
'wtimeoutMS',
332+
/**
333+
* The journal write concern
334+
* @deprecated Please use the `writeConcern` option instead
335+
*/
307336
'journal',
308-
'fsync',
337+
/**
338+
* A MongoDB WriteConcern, which describes the level of acknowledgement
339+
* requested from MongoDB for write operations.
340+
*
341+
* @see https://www.mongodb.com/docs/manual/reference/write-concern/
342+
*/
343+
'writeConcern',
344+
/**
345+
* Validate mongod server certificate against Certificate Authority
346+
* @deprecated Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
347+
*/
348+
'sslValidate',
349+
/**
350+
* SSL Certificate file path.
351+
* @deprecated Will be removed in the next major version. Please use tlsCAFile instead.
352+
*/
353+
'sslCA',
354+
/**
355+
* SSL Certificate file path.
356+
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
357+
*/
358+
'sslCert',
359+
/**
360+
* SSL Key file file path.
361+
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
362+
*/
363+
'sslKey',
364+
/**
365+
* SSL Certificate pass phrase.
366+
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
367+
*/
368+
'sslPass',
369+
/**
370+
* SSL Certificate revocation list file path.
371+
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
372+
*/
373+
'sslCRL',
374+
/** TCP Connection no delay */
375+
'noDelay',
376+
/** @deprecated TCP Connection keep alive enabled. Will not be able to turn off in the future. */
377+
'keepAlive',
378+
/**
379+
* @deprecated The number of milliseconds to wait before initiating keepAlive on the TCP socket.
380+
* Will not be configurable in the future.
381+
*/
382+
'keepAliveInitialDelay',
383+
/** Force server to assign `_id` values instead of driver */
384+
'forceServerObjectId',
385+
/** A primary key factory function for generation of custom `_id` keys */
386+
'pkFactory',
387+
/** Enable command monitoring for this client */
388+
'monitorCommands',
389+
/** Server API version */
390+
'serverApi',
391+
/**
392+
* Optionally enable in-use auto encryption
393+
*
394+
* @remarks
395+
* Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error
396+
* (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
397+
*
398+
* Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
399+
*
400+
* If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
401+
* - AutoEncryptionOptions.keyVaultClient is not passed.
402+
* - AutoEncryptionOptions.bypassAutomaticEncryption is false.
403+
*
404+
* If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
405+
*/
406+
'autoEncryption',
407+
/** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */
408+
'driverInfo',
409+
/** Configures a Socks5 proxy host used for creating TCP connections. */
410+
'proxyHost',
411+
/** Configures a Socks5 proxy port used for creating TCP connections. */
412+
'proxyPort',
413+
/** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
414+
'proxyUsername',
415+
/** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
416+
'proxyPassword',
309417
];
310418

311419
const lbOptions = Object.keys(self.settings);
@@ -338,7 +446,10 @@ MongoDB.prototype.connect = function(callback) {
338446
self.settings.url = urlObj.toString();
339447
}
340448

341-
new mongodb.MongoClient(self.settings.url, validOptions).connect(function(
449+
const mongoClient = new mongodb.MongoClient(self.settings.url, validOptions);
450+
const callbackConnect = util.callbackify(() => mongoClient.connect());
451+
452+
callbackConnect(function(
342453
err,
343454
client,
344455
) {
@@ -586,21 +697,23 @@ MongoDB.prototype.execute = function(modelName, command) {
586697
done(err, result);
587698
};
588699

700+
// from mongoddb v5 command does not support callback
701+
args.pop();
702+
debug('MongoDB: model=%s command=%s', modelName, command, args);
703+
589704
// args had callback removed
590-
if (command === 'find') {
591-
// find does not support callback, remove and use a toArray with this callback
592-
args.pop();
593-
debug('MongoDB: model=%s command=%s', modelName, command, args);
594-
try {
595-
const cursor = collection[command].apply(collection, args);
596-
return observerCallback(null, cursor);
597-
} catch (err) {
598-
return observerCallback(err, null);
705+
try {
706+
const execute = collection[command].apply(collection, args);
707+
708+
if (command === 'find') {
709+
return observerCallback(null, execute);
710+
} else {
711+
const callbackCommand = util.callbackify(() => execute);
712+
713+
return callbackCommand(observerCallback);
599714
}
600-
} else {
601-
args[args.length - 1] = observerCallback;
602-
debug('MongoDB: model=%s command=%s', modelName, command, args);
603-
return collection[command].apply(collection, args);
715+
} catch (err) {
716+
return observerCallback(err, null);
604717
}
605718
},
606719
callback,
@@ -1487,7 +1600,9 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) {
14871600
cursor.skip(filter.offset);
14881601
}
14891602

1490-
cursor.toArray(function(err, data) {
1603+
const callbackCursor = util.callbackify(() => cursor.toArray());
1604+
1605+
callbackCursor(function(err, data) {
14911606
if (self.debug) {
14921607
debug('all', modelName, filter, err, data);
14931608
}
@@ -1557,10 +1672,13 @@ MongoDB.prototype.findOrCreate = function findOrCreate(modelName, filter, data,
15571672

15581673
const projection = fieldsArrayToObj(filter.fields);
15591674

1560-
this.collection(modelName).findOneAndUpdate(
1675+
const callbackFindOneAndUpdate = util.callbackify(() => this.collection(modelName).findOneAndUpdate(
15611676
query,
15621677
{$setOnInsert: data},
15631678
{projection: projection, sort: sort, upsert: true},
1679+
));
1680+
1681+
callbackFindOneAndUpdate(
15641682
function(err, result) {
15651683
if (self.debug) {
15661684
debug('findOrCreate.callback', modelName, filter, err, result);
@@ -1596,7 +1714,7 @@ MongoDB.prototype.findOrCreate = function findOrCreate(modelName, filter, data,
15961714
}
15971715
},
15981716
);
1599-
}
1717+
};
16001718

16011719
/**
16021720
* Transform db data to model entity
@@ -2109,13 +2227,9 @@ MongoDB.prototype.autoupdate = function(models, cb) {
21092227
if (self.debug) {
21102228
debug('createIndex: ', index);
21112229
}
2112-
self
2113-
.collection(modelName)
2114-
.createIndex(
2115-
index.fields || index.keys,
2116-
index.options,
2117-
indexCallback,
2118-
);
2230+
const callbackCreateIndex = util.callbackify(() => self
2231+
.collection(modelName).createIndex(index.fields || index.keys));
2232+
callbackCreateIndex(indexCallback);
21192233
},
21202234
modelCallback,
21212235
);
@@ -2161,7 +2275,9 @@ MongoDB.prototype.automigrate = function(models, cb) {
21612275
debug('drop collection %s for model %s', collectionName, modelName);
21622276
}
21632277

2164-
self.db.dropCollection(collectionName, function(err, collection) {
2278+
const callbackDropCollection = util.callbackify((collectionName) => self.db.dropCollection(collectionName));
2279+
2280+
callbackDropCollection(collectionName, function(err, collection) {
21652281
if (err) {
21662282
debug(
21672283
'Error dropping collection %s for model %s: ',
@@ -2184,7 +2300,10 @@ MongoDB.prototype.automigrate = function(models, cb) {
21842300
if (self.debug) {
21852301
debug('create collection %s for model %s', collectionName, modelName);
21862302
}
2187-
self.db.createCollection(collectionName, modelCallback);
2303+
2304+
const callbackCreateCollection = util.callbackify((collectionName) => self.db
2305+
.createCollection(collectionName));
2306+
callbackCreateCollection(collectionName, modelCallback);
21882307
});
21892308
},
21902309
function(err) {
@@ -2204,7 +2323,7 @@ MongoDB.prototype.automigrate = function(models, cb) {
22042323
MongoDB.prototype.ping = function(cb) {
22052324
const self = this;
22062325
if (self.db) {
2207-
this.db.collection('dummy').findOne({_id: 1}, cb);
2326+
util.callbackify(() => this.db.collection('dummy').findOne({_id: 1}))(cb);
22082327
} else {
22092328
self.dataSource.once('connected', function() {
22102329
self.ping(cb);

0 commit comments

Comments
 (0)