DEV Community

Discussion on: How to initialize a Singleton mongo connection with expressjs

aramix profile image
Aram Bayadyan

if you are using mongoose then you can create a mongoose.js as a middleware where you initialize your connection like so:

const mongoose = require('mongoose');

module.exports = function () {
  const { MONGO_CLUSTER_URL = 'mongodb://', MONGO_DATABASE_NAME } = process.env;

  // Configure mongoose to use Promises, because callbacks are passe.
  mongoose.Promise = global.Promise;
  // Connect to the Mongo DB
  return mongoose.connect(`${MONGO_CLUSTER_URL}/${MONGO_DATABASE_NAME}`, {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
Enter fullscreen mode Exit fullscreen mode

and then in your server.js

const mongooseMiddleware = require('./middlewares/mongoose.js');


  .then(() => createServer(app).listen())
  .catch((err) => {
    // an error occurred connecting to mongo!
    // log the error and exit
    console.error('Unable to connect to mongo.');
Enter fullscreen mode Exit fullscreen mode

you can call any mongoose model after this without initializing the connection again