user5047085
user5047085

Reputation:

Determine if MongoClient instance is already connected

I have this bit of code to check if my MongoClient is already connected:

 connect(): Promise<null> {
    const self = this;

    if (this.client && this.client.isConnected()) {
      return Promise.resolve(null);
    }

    return MongoClient.connect(this.uri).then(function (client) {
      const db = client.db('local');
      self.client = client;
      self.coll = db.collection('oplog.rs');
      return null;
    });
  }

The problem is that the isConnected method takes some mandatory arguments:

    isConnected(name: string, options?: MongoClientCommonOption): boolean; 

here is the info:

http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#isConnected

so do I need to pass anything other than the database name? What if I don't know what database it might be connected to?

When I debug at runtime, I only see an options argument (just 1 argument, not two):

enter image description here

(look at the isConnected method on the far right in the image).

Upvotes: 10

Views: 2654

Answers (2)

Francis Batista
Francis Batista

Reputation: 1520

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 comments
exports.all = (cb) => {
    db = DB.getDB()
    db.collection(COLLECTION).find().toArray(cb)
}

...

See the full node-testing project:

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

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312149

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.

Upvotes: 6

Related Questions