I'm relatively new to Node.js. I'm working with an existing Node.js express application. It creates a new Mongodb Connection as the server starts up and assigns it to a global variable for use elsewhere. All of this works fine.
#In Server.js
async function startServer() {
logger.info("Connecting to the database...");
clientConnect(dbSecrets).then(function (client){
if (!client) {
logger.error("Error connecting to the DB. Shutting down...", new LogMsg(filename, functionName, null, null).toJSON());
process.exit(-1);
}
global.entityDb = client;
.........
#CLient Creation In Mongo.js
clientConnect: async ( dbSecrets ) => (
client = await (() => (new Promise(( resolve, reject ) => (
MongoClient.connect(`mongodb://${dbSecrets.mongoUsername}:${dbSecrets.mongopassword}@${configuration.db.host}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4
},
( error, client ) => {
if ( error ) {
logger.error(error);
reject(error);
}
resolve(client);
})
)
)).catch(( error ) => {
logger.error(`(mongo.js - clientConnect()) - ${error.toString()}`);
return false;
})
)()),
clientClose: async ( client ) => {
client.close();
return true;
},
The values for dbSecrets are injected from a Hashicorp Vault Key Value Secret on application startup and passed into the new MongoClient. I want to update the application to utilise hashicorp vault databases where these username / password values can expire. Is it possible to create the MongoClient so that if the values in dbSecrets are updated then subsequent reconnections to the database will utilise the new values?
could global vars be used for the URI somehow?
FYI this was resolved instead, by not letting the connection expire for the lifetime of the application (container in Kubernetes Pod). It renews the lease on the current credentials before they expire instead of trying to load new credentials.