3

I want build a class for wrapping database connection. This is my code ('db.js' file):

var mongodb = require('mongodb');

var Class = function() {
  this.db = null;
  var server = new mongodb.Server('127.0.0.1', 27017, {auto_reconnect: true});
  db = new mongodb.Db('myDB', server);
  db.open(function(error, db) {
    if (error) {
      console.log('Error ' + error);
    } else {
      console.log('Connected to db.');
      this.db = db;
    }
  });
};

module.exports = Class;

Class.prototype = {
  getCollection: function(coll_name) {
    this.db.collection(coll_name, function(error, c){ // <---  see error below
      return c;
    });
  }
}

exports.oid = mongodb.ObjectID;

Then, my test code ('test.js' file):

var DB = require('./db');
var myDB = new DB();
myDB.getCollection('myCollection'); // <--- error: Cannot call method 'collection' of null
1
  • Is line 2 of your tests file printing Connected to db? Commented Jun 8, 2011 at 16:54

1 Answer 1

1

You are missing "this" in front of "db". eg:

this.db = new mongodb.Db('myDB', server);

And the line next to it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.