node.js 检查猫鼬连接状态而不创建新连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19599543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:05:20  来源:igfitidea点击:

Check mongoose connection state without creating new connection

node.jsmongoose

提问by cyberwombat

I have some tests - namely Supertest - that load my Express app. This app creates a Mongoose connection. I would like to know how to check the status of that connection from within my test.

我有一些测试 - 即 Supertest - 加载我的 Express 应用程序。这个应用程序创建了一个猫鼬连接。我想知道如何从我的测试中检查该连接的状态。

In app.js

在 app.js 中

mongoose.connect(...)

In test.js

在 test.js 中

console.log(mongoose.connection.readyState);

How to access the app.js connection? If I connect using the same parameters in test.js will that create a new connection or look for existing one?

如何访问 app.js 连接?如果我在 test.js 中使用相同的参数进行连接,会创建一个新连接还是查找现有连接?

回答by robertklep

Since the mongoose module exports a singleton object, you don't have to connect in your test.jsto check the state of the connection:

由于 mongoose 模块导出一个单例对象,因此您不必在您的连接中test.js检查连接状态:

// test.js
require('./app.js'); // which executes 'mongoose.connect()'

var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);

ready states being:

就绪状态是:

  • 0: disconnected
  • 1: connected
  • 2: connecting
  • 3: disconnecting
  • 0:断开
  • 1:连接
  • 2:连接
  • 3:断开连接

回答by englishPete

I use this for my Express Server mongoDB status, where I use the express-healthcheck middleware

我将它用于我的 Express Server mongoDB 状态,在那里我使用了 express-healthcheck 中间件

// Define server status
const mongoose = require('mongoose');
const serverStatus = () => {
  return { 
     state: 'up', 
     dbState: mongoose.STATES[mongoose.connection.readyState] 
  }
};
//  Plug into middleware.
api.use('/api/uptime', require('express-healthcheck')({
  healthy: serverStatus
}));

Gives this in a Postman request when the DB is connected.

当数据库连接时,在 Postman 请求中给出这个。

{
  "state": "up",
  "dbState": "connected"
}

Gives this response when the database was shutdown.

当数据库关闭时给出此响应。

{
"state": "up",
"dbState": "disconnected"
}

(The "up" in the responses represent my Express Server status)

(响应中的“up”代表我的 Express Server 状态)

Easy to read (no numbers to interpret)

易于阅读(无需解释数字)