【问题标题】:Check mongoose connection state without creating new connection检查猫鼬连接状态而不创建新连接
【发布时间】:2013-11-05 03:27:57
【问题描述】:

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

在 app.js 中

mongoose.connect(...)

在 test.js 中

console.log(mongoose.connection.readyState);

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

【问题讨论】:

  • 两个脚本是相互独立运行还是app.js需要test.js?
  • @Bernhard test.js 需要 app.js - 在 app.js 我做 var app = exports.app = express() 并且在测试我做 require('../app.js' ).app

标签: node.js mongoose


【解决方案1】:

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

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

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

就绪状态:

  • 0:断开连接
  • 1:已连接
  • 2:连接
  • 3:断开连接

【讨论】:

  • 输出 - 0 = 断开连接,1 = 连接,2 = 连接,3 = 断开连接 (soucre) 我的凭据无效,它给出了 4,我在官方文档或其他任何地方都找不到.
  • @AshwaniAgarwal 查看this file
  • 如果 MongoDB 停止/崩溃,状态仍然保持不变。在我的情况下,如果连接时为 1,并且如果 mongo 停止,它仍在打印 1。
  • @RaviKumarGupta 可能需要(相当)一段时间才能让 Mongoose 知道连接已断开。
  • @robertklep,我是这么认为的。在 mongo 关闭后,我尝试打印就绪状态。即使在 5 分钟后,我仍然可以看到 readyState 值为 1.. :(
【解决方案2】:

我将它用于我的 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
}));

在连接数据库时在 Postman 请求中提供此信息。

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

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

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

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

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

【讨论】:

    【解决方案3】:

    如前所述,“readyState”很好。 “ping”也是很好的管理工具。如果它可以接受命令,它将返回 { ok: 1 }。

    const mongoose = require('mongoose')
    
    // From where ever your making your connection
    const connection = await mongoose.createConnection(
        CONNECT_URI,
        CONNECT_OPTS
    )
    
    async function connectionIsUp(): Promise<boolean> {
        try {
            const adminUtil = connection.db.admin()
    
            const result = await adminUtil.ping()
    
            console.log('result: ', result) // { ok: 1 }
            return !!result?.ok === 1
        } catch(err) {
            return false
        }    
    } 
    

    或者如果你想要它简短。

    async function connectionIsUp(): Promise<boolean> {
        try {
            return await connection.db.admin().ping().then(res => !!res?.ok === 1)
        } catch (err) {
            return false
        }
    }
    

    【讨论】:

    【解决方案4】:
    var dbState = [{
        value: 0,
        label: "disconnected"
    },
    {
        value: 1,
        label: "connected"
    },
    {
        value: 2,
        label: "connecting"
    },
    {
        value: 3,
        label: "disconnecting"
    }];
    
    mongoose.connect(CONNECTIONSTRING, {
        useNewUrlParser: true
    },
    () => {
        const state = Number(mongoose.connection.readyState);
        console.log(dbState.find(f => f.value == state).label, "to db"); // connected to db
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多