I am trying to share the Mongo connection with other modules in my Node.js project. I keep getting either undefined
or is not a function
when attempting to use the exported client. I also had a question around detecting if the connection is in fact open before performing operations on the database.
It seems like using the app.locals
would be the proper way to share the connection but I could not get that working either. Below is what I have at the moment. I’ve tried this many ways. Most of what I can find online seems to export the Mongo Node driver’s method, not the connection itself. The idea is to connect once and never disconnect until the app shuts down.
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function connect () {
app.locals.dbConnected = false;
try {
await client.connect();
app.locals.dbConnected = true;
module.exports = client;
} catch (e) {
console.error(e);
}
};
then in another module do something like:
await client.db('syslogs').collection('production').insertOne(doc);
Is it possible to share the connection?
2
Answers
I just got it working using
app.locals
.index.js
Then in my module:
Could do something like below:
Then in other module you can use the export client like you want.
Thanks.