Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

upgrade mongoose from 5 to 8.8.4 #1676

Merged
merged 16 commits into from
Dec 16, 2024
Prev Previous commit
Next Next commit
clean code
  • Loading branch information
AlvaroVega committed Dec 11, 2024
commit a4f974783685b0aa5da268cc5d7d39e079111078
225 changes: 36 additions & 189 deletions lib/model/dbConn.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ const config = require('../commonConfig');
const constants = require('../constants');
const alarms = require('../services/common/alarmManagement');
const logger = require('logops');
const async = require('async');
const errors = require('../errors');
let defaultDb;
const DEFAULT_DB_NAME = 'iotagent';
Expand Down Expand Up @@ -84,10 +83,39 @@ function init(host, db, port, options, callback) {
mongoose
.connect(url, options)
.then(() => {
//defaultDb = connection.connection;
defaultDb = mongoose.connection;
logger.info(context, 'Successfully connected to MongoDB.');
loadModels();
defaultDb.on('error', function (error) {
logger.error(context, 'Mongo Driver error: %j', error);
alarms.raise(constants.MONGO_ALARM, error);
});
/* eslint-disable-next-line no-unused-vars */
defaultDb.on('connecting', function (error) {
logger.debug(context, 'Mongo Driver connecting');
});
defaultDb.on('connected', function () {
logger.debug(context, 'Mongo Driver connected');
});
defaultDb.on('reconnected', function () {
logger.debug(context, 'Mongo Driver reconnected');
});
defaultDb.on('disconnected', function () {
logger.debug(context, 'Mongo Driver disconnected');
});
defaultDb.on('reconnectFailed', function () {
logger.error(context, 'MONGODB-004: MongoDB connection was lost');
process.exit(1);
});
defaultDb.on('disconnecting', function () {
logger.debug(context, 'Mongo Driver disconnecting');
});
defaultDb.on('open', function () {
logger.debug(context, 'Mongo Driver open');
});
defaultDb.on('close', function () {
logger.debug(context, 'Mongo Driver close');
});
callback();
})
.catch((err) => {
Expand All @@ -99,7 +127,12 @@ function init(host, db, port, options, callback) {
logger.info(context, `Retrying in ${retryTime} seconds...`);
setTimeout(() => connectionAttempt(callback), retryTime * 1000);
} else {
logger.error(context, `MONGODB-002: Failed to connect after ${maxRetries} attempts.`);
logger.error(
context,
'MONGODB-002: Error to connect found after %d attempts: %s',
retries,
lastError
);
callback(err);
}
});
Expand Down Expand Up @@ -143,192 +176,6 @@ function configureDb(callback) {
}
}

// function init(host, db, port, options, callback) {
// /*jshint camelcase:false, validthis:true */
// let url;
// let retries = 0;
// let lastError;
// const maxRetries =
// (config.getConfig().mongodb && config.getConfig().mongodb.retries) || constants.DEFAULT_MONGODB_RETRIES;

// function addPort(item) {
// return item + ':' + port;
// }

// function commaConcat(previous, current, currentIndex) {
// if (currentIndex !== 0) {
// previous += ',';
// }

// previous += current;

// return previous;
// }

// url = 'mongodb://';

// if (options.auth) {
// url += options.auth.user + ':' + options.auth.password + '@';
// }

// const hosts = host.split(',').map(addPort).reduce(commaConcat, '');

// url += hosts + '/' + db;

// if (options.extraArgs) {
// if (options.extraArgs instanceof Object && Object.keys(options.extraArgs).length > 0) {
// url += '?';
// url += Object.entries(options.extraArgs)
// .map(function ([k, v]) {
// return encodeURIComponent(k) + '=' + encodeURIComponent(v);
// })
// .join('&');
// }
// delete options.extraArgs;
// }

// /* eslint-disable-next-line no-unused-vars */
// function createConnectionHandler(error, results) {
// if (defaultDb) {
// logger.info(context, 'Successfully connected to MongoDB.');
// module.exports.db = defaultDb;
// loadModels();
// } else {
// logger.error(context, 'MONGODB-002: Error found after [%d] attempts: %s', retries, error || lastError);
// }

// callback(error);
// }

// function retryCheck() {
// return !defaultDb && retries < maxRetries;
// }

// function connectionAttempt(url, options, callback) {
// logger.info(context, 'Attempting to connect to MongoDB instance with url %j. Attempt %d', url, retries);
// // FIXME: useNewUrlParser is no longer used in underlying mongodb driver 4.x
// // (see https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md)
// // but not sure if current mongoose version is still using mongodb 3.x internally
// // probably mongodb-connectionoptions-test.js needs to be fixed if useNewUrlParser is removed at the end
// options.useNewUrlParser = true;
// options.useUnifiedTopology = true;
// mongoose.set('useCreateIndex', true);
// /* eslint-disable-next-line no-unused-vars */
// const candidateDb = mongoose.createConnection(url, options, function (error, result) {
// if (error) {
// logger.error(context, 'MONGODB-001: Error trying to connect to MongoDB: %s', error);
// lastError = error;
// } else {
// defaultDb = candidateDb;

// defaultDb.on('error', function (error) {
// logger.error(context, 'Mongo Driver error: %j', error);
// alarms.raise(constants.MONGO_ALARM, error);
// });
// /* eslint-disable-next-line no-unused-vars */
// defaultDb.on('connecting', function (error) {
// logger.debug(context, 'Mongo Driver connecting');
// });

// defaultDb.on('connected', function () {
// logger.debug(context, 'Mongo Driver connected');
// });
// defaultDb.on('reconnected', function () {
// logger.debug(context, 'Mongo Driver reconnected');
// });
// defaultDb.on('disconnected', function () {
// logger.debug(context, 'Mongo Driver disconnected');
// });
// defaultDb.on('reconnectFailed', function () {
// logger.error(context, 'MONGODB-004: MongoDB connection was lost');
// process.exit(1);
// });
// defaultDb.on('disconnecting', function () {
// logger.debug(context, 'Mongo Driver disconnecting');
// });
// defaultDb.on('open', function () {
// logger.debug(context, 'Mongo Driver open');
// });
// defaultDb.on('close', function () {
// logger.debug(context, 'Mongo Driver close');
// });
// }

// callback();
// });
// }

// function tryCreateConnection(callback) {
// const attempt = async.apply(connectionAttempt, url, options, callback);
// const seconds =
// (config.getConfig().mongodb && config.getConfig().mongodb.retryTime) ||
// constants.DEFAULT_MONGODB_RETRY_TIME;

// retries++;

// if (retries === 1) {
// logger.info(context, 'First connection attempt');
// attempt();
// } else {
// logger.info(context, 'Waiting %d seconds before attempting again.', seconds);
// setTimeout(attempt, seconds * 1000);
// }
// }

// defaultDb = null;
// async.whilst(retryCheck, tryCreateConnection, createConnectionHandler);
// }

// function configureDb(callback) {
// /*jshint camelcase:false, validthis:true */
// const currentConfig = config.getConfig();

// if (currentConfig.deviceRegistry && currentConfig.deviceRegistry.type === 'mongodb') {
// if (!currentConfig.mongodb || !currentConfig.mongodb.host) {
// logger.fatal(context, 'MONGODB-003: No host found for MongoDB driver.');
// callback(new errors.BadConfiguration('No host found for MongoDB driver'));
// } else {
// let dbName = currentConfig.mongodb.db;
// const port = currentConfig.mongodb.port || 27017;
// const options = {};

// if (!currentConfig.mongodb.db) {
// dbName = DEFAULT_DB_NAME;
// }

// if (currentConfig.mongodb.replicaSet) {
// options.replicaSet = currentConfig.mongodb.replicaSet;
// }

// if (currentConfig.mongodb.ssl) {
// options.ssl = currentConfig.mongodb.ssl;
// }

// if (currentConfig.mongodb.extraArgs) {
// options.extraArgs = currentConfig.mongodb.extraArgs;
// }

// if (currentConfig.mongodb.user && currentConfig.mongodb.password) {
// options.auth = {};
// options.auth.user = currentConfig.mongodb.user;
// options.auth.password = currentConfig.mongodb.password;
// // authSource only applies if auth is set
// if (currentConfig.mongodb.authSource) {
// // Overload extraArgs if it was set
// options.extraArgs = {
// ...options.extraArgs,
// authSource: currentConfig.mongodb.authSource
// };
// }
// }

// init(config.getConfig().mongodb.host, dbName, port, options, callback);
// }
// } else {
// callback();
// }
// }

exports.configureDb = configureDb;
exports.db = defaultDb;
exports.DEFAULT_DB_NAME = DEFAULT_DB_NAME;
Loading
Loading