Determine if MongoClient instance is already connected Determine if MongoClient instance is already connected mongodb mongodb

Determine if MongoClient instance is already connected


The documentation is incorrect. Looking at the source code (line 395), the only supported parameter is an optional options object.

MongoClient.prototype.isConnected = function(options) {  options = options || {};  if (!this.topology) return false;  return this.topology.isConnected(options);};

So ignore the docs and don't pass a database name.


I have a suggestion about that:

const MongoClient = require('mongodb').MongoClient    , async = require('async')const state = {    db: null,    mode: null,}// In the real world it will be better if the production uri comes// from an environment variable, instead of being hard coded.const PRODUCTION_URI = 'mongodb://127.0.0.1:27018/production'    , TEST_URI = 'mongodb://127.0.0.1:27018/test'exports.MODE_TEST = 'mode_test'exports.MODE_PRODUCTION = 'mode_production'// To connect to either the production or the test database.exports.connect = (mode, done) => {    if (state.db) {        return done()    }    const uri = mode === exports.MODE_TEST ? TEST_URI : PRODUCTION_URI    MongoClient.connect(uri, (err, db) => {        if (err) {            return done(err)        }        state.db = db        state.mode = mode        done()    })}

You can call the database in your models as below:

const DB = require('../db')const COLLECTION = 'comments'let db// Get all commentsexports.all = (cb) => {    db = DB.getDB()    db.collection(COLLECTION).find().toArray(cb)}...

See the full node-testing project:

https://github.com/francisrod01/node-testing