【问题标题】:Node.js/JavaScript wait until required module has completed runningNode.js/JavaScript 等到所需模块完成运行
【发布时间】:2020-06-26 20:38:30
【问题描述】:

我有一个 express.js 应用程序,它使用 mongoose 连接 MongoDB。目前,我有猫鼬代码在一个单独的文件中连接数据库,因为它的东西经常跨模块使用
这是连接器的代码

const mongoose = require("mongoose");

let host = process.env.DB_HOST;
let port = process.env.DB_PORT;
let name = process.env.DB_NAME;

mongoose
 .connect(`mongodb://${host}:${port}/${name}`, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
 })
 .then(() => {
     console.log("Connection established with DB");
 })
 .catch(error => {
     console.log(`Error in conecting to database!\n${error}`);
 });

然后我需要在我的主 app.js 文件中使用

require("./database/connector")

之后用

启动 express 服务器
app.listen(PORT,()=>{console.log(`server started at port ${PORT}`);})

虽然运行正常,但我得到的输出是

   server started at port 3000
   Connections established with DB

这基本上意味着数据库连接发生在服务器启动后 由于我现在不会深入探讨的原因,我需要一种方法来确保服务器在建立数据库连接之前不接受任何请求(这不是必需的,但它会使我的测试过程更容易为了处理,我使用 jest 和 supertest 进行测试)

实现此目的的最佳方法是什么?

【问题讨论】:

  • 您的代码必须有更多内容,因为没有人可以在您展示的内容中使用连接的数据库。因此,也许您需要将数据库连接本身与其他模块进行通信,然后可以导出解析为数据库连接对象本身的 Promise。然后,任何导入的人都可以使用该承诺来知道何时完成连接并获取连接的数据库对象。

标签: node.js mongodb express asynchronous mongoose


【解决方案1】:

有两种选择:

  1. 直接绑定监听数据库连接事件的服务器端口,或者从数据库模块返回并传递promise或事件发射器到web应用模块。
mongoose
 .connect(`mongodb://${host}:${port}/${name}`, {
    //...
 })
 .then(() => {
    app.listen(PORT,()=>{console.log(`server started at port ${PORT}`);})
 })
  1. 向您的 express.js Web 应用程序添加一个中间件,用于检查数据库服务器是否已连接。 (它应该作为第一条路由添加到路由器中。)
var app = express();

// the first route
app.use((req, res, next) => {
  // if database connected, continue using following routes
  if (mongoose.connection.readyState == 1) return next();
  // otherwisetell people the server isn't ready.
  res.status(500);
  res.end();
})

// continue what you were doing before
app.use(...)
app.all('/some-path', ...)

app.listen(PORT,()=>{console.log(`server started at port ${PORT}`);})


【讨论】:

    猜你喜欢
    • 2016-03-04
    • 2015-08-13
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    相关资源
    最近更新 更多