Database connection error (mongo and nodejs)

I want to create a class to connect to a database. 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
+3
source share
1 answer

You are missing "this" before "db". eg:

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

And a line next to her.

+1
source

All Articles