Skip to content

Commit cf0e199

Browse files
mrbatistadhmlau
authored andcommitted
feat: upgrade mongodb driver to version 5.x
Signed-off-by: Matteo Padovano <6544817+mrbatista@users.noreply.github.com>
1 parent 74cd2e7 commit cf0e199

File tree

4 files changed

+308
-270
lines changed

4 files changed

+308
-270
lines changed

lib/mongodb.js

Lines changed: 205 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -231,82 +231,189 @@ MongoDB.prototype.connect = function(callback) {
231231
});
232232
});
233233
} else {
234-
// 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
235235
const validOptionNames = [
236-
'poolSize',
237-
'ssl',
238-
'sslValidate',
239-
'sslCA',
240-
'sslCert',
241-
'sslKey',
242-
'sslPass',
243-
'sslCRL',
236+
'replicaSet',
237+
/** Enables or disables TLS/SSL for the connection. */
244238
'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. */
245247
'tlsCertificateKeyFile',
248+
/** Specifies the password to de-crypt the tlsCertificateKeyFile. */
246249
'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 */
247253
'tlsAllowInvalidCertificates',
254+
/** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
248255
'tlsAllowInvalidHostnames',
256+
/** Disables various certificate validations. */
249257
'tlsInsecure',
250-
'tlsCAFile',
251-
'autoReconnect',
252-
'noDelay',
253-
'keepAlive',
254-
'keepAliveInitialDelay',
258+
/** The time in milliseconds to attempt a connection before timing out. */
255259
'connectTimeoutMS',
256-
'serverSelectionTimeoutMS',
257-
'family',
260+
/** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
258261
'socketTimeoutMS',
259-
'reconnectTries',
260-
'reconnectInterval',
261-
'ha',
262-
'haInterval',
263-
'replicaSet',
264-
'secondaryAcceptableLatencyMS',
265-
'acceptableLatencyMS',
266-
'connectWithNoPrimary',
267-
'authSource',
268-
'forceServerObjectId',
269-
'serializeFunctions',
270-
'ignoreUndefined',
271-
'raw',
272-
'bufferMaxEntries',
273-
'readPreference',
274-
'pkFactory',
275-
'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) */
276287
'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. */
277293
'maxStalenessSeconds',
278-
'loggerLevel',
279-
'logger',
280-
'promoteValues',
281-
'promoteBuffers',
282-
'promoteLongs',
283-
'domainsEnabled',
284-
'checkServerIdentity',
285-
'validateOptions',
286-
'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. */
287297
'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. */
288301
'authMechanism',
289-
'compression',
290-
'readPreferenceTags',
291-
'numberOfRetries',
292-
'auto_reconnect',
293-
'minSize',
294-
'useNewUrlParser',
295-
'useUnifiedTopology',
296-
'writeConcern',
297-
// Ignored options
298-
'native_parser',
299-
// Legacy options
300-
'server',
301-
'replset',
302-
'replSet',
303-
'mongos',
304-
'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+
*/
305326
'w',
306-
'wtimeout',
307-
'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+
*/
308336
'journal',
309-
'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',
310417
];
311418

312419
const lbOptions = Object.keys(self.settings);
@@ -339,7 +446,10 @@ MongoDB.prototype.connect = function(callback) {
339446
self.settings.url = urlObj.toString();
340447
}
341448

342-
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(
343453
err,
344454
client,
345455
) {
@@ -587,21 +697,23 @@ MongoDB.prototype.execute = function(modelName, command) {
587697
done(err, result);
588698
};
589699

700+
// from mongoddb v5 command does not support callback
701+
args.pop();
702+
debug('MongoDB: model=%s command=%s', modelName, command, args);
703+
590704
// args had callback removed
591-
if (command === 'find') {
592-
// find does not support callback, remove and use a toArray with this callback
593-
args.pop();
594-
debug('MongoDB: model=%s command=%s', modelName, command, args);
595-
try {
596-
const cursor = collection[command].apply(collection, args);
597-
return observerCallback(null, cursor);
598-
} catch (err) {
599-
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);
600714
}
601-
} else {
602-
args[args.length - 1] = observerCallback;
603-
debug('MongoDB: model=%s command=%s', modelName, command, args);
604-
return collection[command].apply(collection, args);
715+
} catch (err) {
716+
return observerCallback(err, null);
605717
}
606718
},
607719
callback,
@@ -1488,7 +1600,9 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) {
14881600
cursor.skip(filter.offset);
14891601
}
14901602

1491-
cursor.toArray(function(err, data) {
1603+
const callbackCursor = util.callbackify(() => cursor.toArray());
1604+
1605+
callbackCursor(function(err, data) {
14921606
if (self.debug) {
14931607
debug('all', modelName, filter, err, data);
14941608
}
@@ -1558,10 +1672,13 @@ MongoDB.prototype.findOrCreate = function findOrCreate(modelName, filter, data,
15581672

15591673
const projection = fieldsArrayToObj(filter.fields);
15601674

1561-
this.collection(modelName).findOneAndUpdate(
1675+
const callbackFindOneAndUpdate = util.callbackify(() => this.collection(modelName).findOneAndUpdate(
15621676
query,
15631677
{$setOnInsert: data},
15641678
{projection: projection, sort: sort, upsert: true},
1679+
));
1680+
1681+
callbackFindOneAndUpdate(
15651682
function(err, result) {
15661683
if (self.debug) {
15671684
debug('findOrCreate.callback', modelName, filter, err, result);
@@ -2110,13 +2227,9 @@ MongoDB.prototype.autoupdate = function(models, cb) {
21102227
if (self.debug) {
21112228
debug('createIndex: ', index);
21122229
}
2113-
self
2114-
.collection(modelName)
2115-
.createIndex(
2116-
index.fields || index.keys,
2117-
index.options,
2118-
indexCallback,
2119-
);
2230+
const callbackCreateIndex = util.callbackify(() => self
2231+
.collection(modelName).createIndex(index.fields || index.keys));
2232+
callbackCreateIndex(indexCallback);
21202233
},
21212234
modelCallback,
21222235
);
@@ -2162,7 +2275,9 @@ MongoDB.prototype.automigrate = function(models, cb) {
21622275
debug('drop collection %s for model %s', collectionName, modelName);
21632276
}
21642277

2165-
self.db.dropCollection(collectionName, function(err, collection) {
2278+
const callbackDropCollection = util.callbackify((collectionName) => self.db.dropCollection(collectionName));
2279+
2280+
callbackDropCollection(collectionName, function(err, collection) {
21662281
if (err) {
21672282
debug(
21682283
'Error dropping collection %s for model %s: ',
@@ -2185,7 +2300,10 @@ MongoDB.prototype.automigrate = function(models, cb) {
21852300
if (self.debug) {
21862301
debug('create collection %s for model %s', collectionName, modelName);
21872302
}
2188-
self.db.createCollection(collectionName, modelCallback);
2303+
2304+
const callbackCreateCollection = util.callbackify((collectionName) => self.db
2305+
.createCollection(collectionName));
2306+
callbackCreateCollection(collectionName, modelCallback);
21892307
});
21902308
},
21912309
function(err) {
@@ -2205,7 +2323,7 @@ MongoDB.prototype.automigrate = function(models, cb) {
22052323
MongoDB.prototype.ping = function(cb) {
22062324
const self = this;
22072325
if (self.db) {
2208-
this.db.collection('dummy').findOne({_id: 1}, cb);
2326+
util.callbackify(() => this.db.collection('dummy').findOne({_id: 1}))(cb);
22092327
} else {
22102328
self.dataSource.once('connected', function() {
22112329
self.ping(cb);

0 commit comments

Comments
 (0)