Skip to content

Commit

Permalink
feat: upgrade mongodb driver to version 5.x
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Padovano <6544817+mrbatista@users.noreply.github.com>
  • Loading branch information
mrbatista committed Feb 6, 2025
1 parent fe4a2f9 commit 613cfe7
Show file tree
Hide file tree
Showing 4 changed files with 391 additions and 329 deletions.
297 changes: 208 additions & 89 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,8 @@ function MongoDB(settings, dataSource) {
this.settings.enableOptimizedfindOrCreate === true ||
this.settings.enableOptimizedFindOrCreate === true
) {
debug('Optimized findOrCreate is enabled by default, and the enableOptimizedFindOrCreate setting is ignored since v7.0.0.')
debug('Optimized findOrCreate is enabled by default, and the enableOptimizedFindOrCreate setting ' +
'is ignored since v7.0.0.');
}

if (this.settings.enableGeoIndexing === true) {
Expand Down Expand Up @@ -230,82 +231,189 @@ MongoDB.prototype.connect = function(callback) {
});
});
} else {
// See https://github.com/mongodb/node-mongodb-native/blob/3.7/lib/mongo_client.js#L94
// See https://www.mongodb.com/docs/manual/reference/connection-string
const validOptionNames = [
'poolSize',
'ssl',
'sslValidate',
'sslCA',
'sslCert',
'sslKey',
'sslPass',
'sslCRL',
'replicaSet',
/** Enables or disables TLS/SSL for the connection. */
'tls',
/** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
'ssl',
/**
* Specifies the location of a local TLS Certificate
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'tlsCertificateFile',
/** 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. */
'tlsCertificateKeyFile',
/** Specifies the password to de-crypt the tlsCertificateKeyFile. */
'tlsCertificateKeyFilePassword',
/** 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. */
'tlsCAFile',
/** Bypasses validation of the certificates presented by the mongod/mongos instance */
'tlsAllowInvalidCertificates',
/** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
'tlsAllowInvalidHostnames',
/** Disables various certificate validations. */
'tlsInsecure',
'tlsCAFile',
'autoReconnect',
'noDelay',
'keepAlive',
'keepAliveInitialDelay',
/** The time in milliseconds to attempt a connection before timing out. */
'connectTimeoutMS',
'serverSelectionTimeoutMS',
'family',
/** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
'socketTimeoutMS',
'reconnectTries',
'reconnectInterval',
'ha',
'haInterval',
'replicaSet',
'secondaryAcceptableLatencyMS',
'acceptableLatencyMS',
'connectWithNoPrimary',
'authSource',
'forceServerObjectId',
'serializeFunctions',
'ignoreUndefined',
'raw',
'bufferMaxEntries',
'readPreference',
'pkFactory',
'promiseLibrary',
/** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
'compressors',
/** An integer that specifies the compression level if using zlib for network compression. */
'zlibCompressionLevel',
/** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
'srvMaxHosts',
/**
* Modifies the srv URI to look like:
*
* `_{srvServiceName}._tcp.{hostname}.{domainname}`
*
* Querying this DNS URI is expected to respond with SRV records
*/
'srvServiceName',
/** The maximum number of connections in the connection pool. */
'maxPoolSize',
/** The minimum number of connections in the connection pool. */
'minPoolSize',
/** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
'maxConnecting',
/** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */
'maxIdleTimeMS',
/** The maximum time in milliseconds that a thread can wait for a connection to become available. */
'waitQueueTimeoutMS',
/** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
'readConcern',
/** The level of isolation */
'readConcernLevel',
/** Specifies the read preferences for this connection */
'readPreference',
/** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
'maxStalenessSeconds',
'loggerLevel',
'logger',
'promoteValues',
'promoteBuffers',
'promoteLongs',
'domainsEnabled',
'checkServerIdentity',
'validateOptions',
'appname',
/** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */
'readPreferenceTags',
/** The auth settings for when connection to server. */
'auth',
/** Specify the database name associated with the user’s credentials. */
'authSource',
/** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
'authMechanism',
'compression',
'readPreferenceTags',
'numberOfRetries',
'auto_reconnect',
'minSize',
'useNewUrlParser',
'useUnifiedTopology',
'writeConcern',
// Ignored options
'native_parser',
// Legacy options
'server',
'replset',
'replSet',
'mongos',
'db',
/** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
'authMechanismProperties',
/** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
'localThresholdMS',
/** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
'serverSelectionTimeoutMS',
/** 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. */
'heartbeatFrequencyMS',
/** 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. */
'minHeartbeatFrequencyMS',
/** 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 */
'appName',
/** Enables retryable reads. */
'retryReads',
/** Enable retryable writes. */
'retryWrites',
/** Allow a driver to force a Single topology type with a connection string containing one host */
'directConnection',
/** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
'loadBalanced',
/**
* The write concern w value
* @deprecated Please use the `writeConcern` option instead
*/
'w',
'wtimeout',
'j',
/**
* The write concern timeout
* @deprecated Please use the `writeConcern` option instead
*/
'wtimeoutMS',
/**
* The journal write concern
* @deprecated Please use the `writeConcern` option instead
*/
'journal',
'fsync',
/**
* A MongoDB WriteConcern, which describes the level of acknowledgement
* requested from MongoDB for write operations.
*
* @see https://www.mongodb.com/docs/manual/reference/write-concern/
*/
'writeConcern',
/**
* Validate mongod server certificate against Certificate Authority
* @deprecated Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
*/
'sslValidate',
/**
* SSL Certificate file path.
* @deprecated Will be removed in the next major version. Please use tlsCAFile instead.
*/
'sslCA',
/**
* SSL Certificate file path.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'sslCert',
/**
* SSL Key file file path.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'sslKey',
/**
* SSL Certificate pass phrase.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
*/
'sslPass',
/**
* SSL Certificate revocation list file path.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'sslCRL',
/** TCP Connection no delay */
'noDelay',
/** @deprecated TCP Connection keep alive enabled. Will not be able to turn off in the future. */
'keepAlive',
/**
* @deprecated The number of milliseconds to wait before initiating keepAlive on the TCP socket.
* Will not be configurable in the future.
*/
'keepAliveInitialDelay',
/** Force server to assign `_id` values instead of driver */
'forceServerObjectId',
/** A primary key factory function for generation of custom `_id` keys */
'pkFactory',
/** Enable command monitoring for this client */
'monitorCommands',
/** Server API version */
'serverApi',
/**
* Optionally enable in-use auto encryption
*
* @remarks
* 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
* (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.
*
* Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
*
* 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:
* - AutoEncryptionOptions.keyVaultClient is not passed.
* - AutoEncryptionOptions.bypassAutomaticEncryption is false.
*
* 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.
*/
'autoEncryption',
/** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */
'driverInfo',
/** Configures a Socks5 proxy host used for creating TCP connections. */
'proxyHost',
/** Configures a Socks5 proxy port used for creating TCP connections. */
'proxyPort',
/** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
'proxyUsername',
/** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
'proxyPassword',
];

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

new mongodb.MongoClient(self.settings.url, validOptions).connect(function(
const mongoClient = new mongodb.MongoClient(self.settings.url, validOptions);
const callbackConnect = util.callbackify(() => mongoClient.connect());

callbackConnect(function(
err,
client,
) {
Expand Down Expand Up @@ -586,21 +697,23 @@ MongoDB.prototype.execute = function(modelName, command) {
done(err, result);
};

// from mongoddb v5 command does not support callback
args.pop();
debug('MongoDB: model=%s command=%s', modelName, command, args);

// args had callback removed
if (command === 'find') {
// find does not support callback, remove and use a toArray with this callback
args.pop();
debug('MongoDB: model=%s command=%s', modelName, command, args);
try {
const cursor = collection[command].apply(collection, args);
return observerCallback(null, cursor);
} catch (err) {
return observerCallback(err, null);
try {
const execute = collection[command].apply(collection, args);

if (command === 'find') {
return observerCallback(null, execute);
} else {
const callbackCommand = util.callbackify(() => execute);

return callbackCommand(observerCallback);
}
} else {
args[args.length - 1] = observerCallback;
debug('MongoDB: model=%s command=%s', modelName, command, args);
return collection[command].apply(collection, args);
} catch (err) {
return observerCallback(err, null);
}
},
callback,
Expand Down Expand Up @@ -1487,7 +1600,9 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) {
cursor.skip(filter.offset);
}

cursor.toArray(function(err, data) {
const callbackCursor = util.callbackify(() => cursor.toArray());

callbackCursor(function(err, data) {
if (self.debug) {
debug('all', modelName, filter, err, data);
}
Expand Down Expand Up @@ -1557,10 +1672,13 @@ MongoDB.prototype.findOrCreate = function findOrCreate(modelName, filter, data,

const projection = fieldsArrayToObj(filter.fields);

this.collection(modelName).findOneAndUpdate(
const callbackFindOneAndUpdate = util.callbackify(() => this.collection(modelName).findOneAndUpdate(
query,
{$setOnInsert: data},
{projection: projection, sort: sort, upsert: true},
));

callbackFindOneAndUpdate(
function(err, result) {
if (self.debug) {
debug('findOrCreate.callback', modelName, filter, err, result);
Expand Down Expand Up @@ -1596,7 +1714,7 @@ MongoDB.prototype.findOrCreate = function findOrCreate(modelName, filter, data,
}
},
);
}
};

/**
* Transform db data to model entity
Expand Down Expand Up @@ -2109,13 +2227,9 @@ MongoDB.prototype.autoupdate = function(models, cb) {
if (self.debug) {
debug('createIndex: ', index);
}
self
.collection(modelName)
.createIndex(
index.fields || index.keys,
index.options,
indexCallback,
);
const callbackCreateIndex = util.callbackify(() => self
.collection(modelName).createIndex(index.fields || index.keys));
callbackCreateIndex(indexCallback);
},
modelCallback,
);
Expand Down Expand Up @@ -2161,7 +2275,9 @@ MongoDB.prototype.automigrate = function(models, cb) {
debug('drop collection %s for model %s', collectionName, modelName);
}

self.db.dropCollection(collectionName, function(err, collection) {
const callbackDropCollection = util.callbackify((collectionName) => self.db.dropCollection(collectionName));

callbackDropCollection(collectionName, function(err, collection) {
if (err) {
debug(
'Error dropping collection %s for model %s: ',
Expand All @@ -2184,7 +2300,10 @@ MongoDB.prototype.automigrate = function(models, cb) {
if (self.debug) {
debug('create collection %s for model %s', collectionName, modelName);
}
self.db.createCollection(collectionName, modelCallback);

const callbackCreateCollection = util.callbackify((collectionName) => self.db
.createCollection(collectionName));
callbackCreateCollection(collectionName, modelCallback);
});
},
function(err) {
Expand All @@ -2204,7 +2323,7 @@ MongoDB.prototype.automigrate = function(models, cb) {
MongoDB.prototype.ping = function(cb) {
const self = this;
if (self.db) {
this.db.collection('dummy').findOne({_id: 1}, cb);
util.callbackify(() => this.db.collection('dummy').findOne({_id: 1}))(cb);
} else {
self.dataSource.once('connected', function() {
self.ping(cb);
Expand Down
Loading

0 comments on commit 613cfe7

Please sign in to comment.