连接数据库时出错(mongo和nodejs)

时间:2011-06-07 16:54:48

标签: mongodb node.js

我想构建一个包装数据库连接的类。这是我的代码('db.js'文件):

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;

然后,我的测试代码('test.js'文件):

var DB = require('./db');
var myDB = new DB();
myDB.getCollection('myCollection'); // <--- error: Cannot call method 'collection' of null

1 个答案:

答案 0 :(得分:1)

你在“db”前面缺少“this”。例如:

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

旁边有一条线。

相关问题