Check mongoose connection state without creating new connection

后端 未结 2 1455
离开以前
离开以前 2021-01-30 12:43

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 wit

2条回答
  •  野性不改
    2021-01-30 12:51

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

    // 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.

    {
      "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)

    Easy to read (no numbers to interpret)

提交回复
热议问题