Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there is an existing MongoDB connection using mongoose?

I have an express app that connects to MongoDB via mongoose, and I also have an init script that will occasionally connect to MongoDB.

Is there any way to detect if there is an existing connection to the DB, so I will not need to connect again in the script anytime I want to run it, also is there any consequences for connecting to the DB multiple times via mongoose.

like image 992
hisabimbola Avatar asked Sep 06 '25 03:09

hisabimbola


1 Answers

you can check this using mongoose.connection.readyState,

ex.

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

The state would return 1 if already connected.

like image 65
Naeem Shaikh Avatar answered Sep 09 '25 14:09

Naeem Shaikh