开发者

Error in connecting database (mongo and nodejs)

I want build a class for wrapping database connection. Th开发者_JS百科is 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


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

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

And the line next to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜