连接数据库错误(mongo和nodejs)

3
我希望建立一个用于封装数据库连接的类。这是我的代码('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

你的测试文件第二行是否打印了“已连接到数据库”? - Gates VP
1个回答

1

你忘了在“db”前面加上“this”。例如:

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

并且它旁边的那一行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接