Home > Blockchain >  Node.js/Express: How Do I Share or Export Mongo Database Connection To Other Modules?
Node.js/Express: How Do I Share or Export Mongo Database Connection To Other Modules?

Time:11-24

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?

CodePudding user response:

Could do something like below:

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let __inst = null;

export default new Promise((resolve, reject) => {
  if (__inst !== null) resolve(__inst);

  // the open event is the key here
  // like this we can handle error, close etc thru events as well
  client.open((err, mongoInst) => {
    if (err) reject(err);
    __inst = mongoInst;
    resolve(__inst);
  });
});

Then in other module you can use the export client like you want.

Thanks.

CodePudding user response:

I just got it working using app.locals.

index.js

const { MongoClient } = require("mongodb");
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
(async () => {
    app.locals.dbConnected = false;
    try {
        await client.connect();
        console.log("Connected to DB");
        app.locals.client = client;
        app.listen(PORT, HOST, () => {
          console.log(`Running on http://${HOST}:${PORT}`);
        });
    } catch (e) {
        console.error(e);
    }
})();

Then in my module:

async function index (req, res) {
  try {
    let db = req.app.locals.client.db("admin");
    await db.command({ ping: 1 });
    console.log("pinged admin database");
  }catch(err) {
  console.log(err);
  }
}
  • Related