Check mongoose connection state without creating new connection

node.jsMongoose

node.js Problem Overview


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.

In app.js

mongoose.connect(...)

In 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?

node.js Solutions


Solution 1 - node.js

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

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

Solution 2 - node.js

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)

Solution 3 - node.js

As stated before "readyState" is good. "ping" is also good admin utility for doing so as well. It will return { ok: 1 } if it can accept commands.

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

Or if you you want it short.

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

Solution 4 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncyberwombatView Question on Stackoverflow
Solution 1 - node.jsrobertklepView Answer on Stackoverflow
Solution 2 - node.jsenglishPeteView Answer on Stackoverflow
Solution 3 - node.jsMardokView Answer on Stackoverflow
Solution 4 - node.jsKemal AkçılView Answer on Stackoverflow