DEV Community

Discussion on: Open Multiple MongoDB connection in Express.js App

Collapse
 
ziishaned profile image
Zeeshan Ahmd • Edited

@vigneshncc can you share your source code

Collapse
 
vigneshncc profile image
Vignesh Gopalakrishnan

Hello Zeeshan, Thanks for your code snippet. I took yours as a reference and I ended up changing it accordingly which suits for typescript. I made it very simple for now to work and that is why I haven't added the types fully.

The below code block works fine, except the commented one. All 'this' inside the functions are throwing error and would be great if you help me where I am doing wrong.

import mongoose from "mongoose";
import logger from "./logger";

const makeNewConnection = (uri: string): mongoose.Connection => {
  let conn: mongoose.Connection = mongoose.createConnection(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  });

  /* conn.on("error", function (error) {
    logger.info(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
    conn
      .close()
      .catch(() =>
        logger.warn(`MongoDB :: failed to close connection ${this.name}`)
      );
  });

  conn.on("connected", function () {
    mongoose.set("debug", function (col, method, query, doc) {
      logger.debug(
        `MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(
          query
        )},${JSON.stringify(doc)})`
      );
    });
    logger.info(`MongoDB :: connected ${this.name}`);
  });

  conn.on("disconnected", function () {
    logger.info(`MongoDB :: disconnected ${this.name}`);
  }); */

  return conn;
};

const dbOne= makeNewConnection(process.env.DB_ONE);
const dbTwo = makeNewConnection(process.env.DB_TWO);

export { dbOne, dbTwo };
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
piotrmonsiorski profile image
Piotr Monsiorski

It's quite old question, but this may help someone in the future: check if your process.env variables aren't undefined. To fix this, you can move dotenv.config(); to connections.js file and use in before makeNewConnection(...) function.