如何从快速服务器启动中解耦 mongodb atlas 连接

how to decouple mongodb atlas connection from the express server start

我试图将我的快速服务器从 mongodb 连接进程中分离出来。

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`)
  })
})

所以我想要两个文件,一个用于 mongodb 连接,另一个用于启动服务器,而不是这个单一文件。当我这样做时,我得到了与 mongodb 相关的错误,我想是因为服务器甚至在 mongodb 连接建立之前就启动了。

关于如何解决这个问题的任何想法

将它包装在一个 promise 中并在任何你想调用的地方调用它

创建一个文件名db.js,无论您想要什么,都可以在您需要的文件中使用。然后将回调包装在一个承诺中,并将其导出以供在文件外部使用。上面的例子。

 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 };

然后在你的初始化函数中,你可以调用

   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`)
        })
  }