简体   繁体   中英

how to decouple mongodb atlas connection from the express server start

Im trying to decouple my express server start from the mongodb connection process .

mongodb.connect(process.env.CONNECTIONSTRING, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
  if (err) {
    throw new Error(err)
  }
  module.exports = client

  

  const server = require("./server")

  server.start(opts, t => {
    console.log(`server is up 4000`)
  })
})

so instead of this single file I would like to have two files one used for mongodb connection , and other for starting the server . when i did this I got error related to mongodb, I think because the server started even before the mongodb conection was established.

any idea on how to solve this

Wrap it in a promise and call it wherever you want

Create a file name db.js it whatever else you want and require in the file that you need it. Then wrap the callback in a promise and export it for usage outside the file. Example above.

 function initMongo() {
  mongodb.connect(process.env.CONNECTIONSTRING, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {

   return new Promise((resolve, reject) => {
    if (err) {
       return reject(err);
    }
    return resolve(client)
   })
  })
}

 module.exports = { initMongo };

Then in your init function, you could call

   const server = require("./server");
   const mongoDb = require("./db");

  async init() {
        let client;
        try {
              client = await mongoDb.initMongo()
        } catch(e) {
               // could not connect to db
         }

        server.start(opts, t => {
            console.log(`server is up 4000`)
        })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM