连接数据库时发生错误(mongo和nodejs)
问题描述:
我想构建一个包装数据库连接的类。这是我的代码( 'db.js' 文件):连接数据库时发生错误(mongo和nodejs)
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
答
你缺少前面的 “这个” “D b”。例如:
this.db = new mongodb.Db('myDB', server);
和旁边的行。
您的测试文件的第2行是否打印“连接到数据库”? – 2011-06-08 16:54:43