Mongodb 连接数据库时出错(mongo和nodejs)
我想构建一个用于包装数据库连接的类。这是我的代码('db.js'文件):Mongodb 连接数据库时出错(mongo和nodejs),mongodb,node.js,Mongodb,Node.js,我想构建一个用于包装数据库连接的类。这是我的代码('db.js'文件): var mongodb=require('mongodb'); var类=函数(){ this.db=null; var server=newmongodb.server('127.0.0.1',27017,{auto_reconnect:true}); db=newmongodb.db('myDB',server); db.open(函数(错误,db){ 如果(错误){ console.log('Error'+Error
var mongodb=require('mongodb');
var类=函数(){
this.db=null;
var server=newmongodb.server('127.0.0.1',27017,{auto_reconnect:true});
db=newmongodb.db('myDB',server);
db.open(函数(错误,db){
如果(错误){
console.log('Error'+Error);
}否则{
log('连接到数据库');
这个.db=db;
}
});
};
module.exports=类;
Class.prototype={
getCollection:函数(coll_名称){
this.db.collection(coll_name,function(error,c){/在“db”前面缺少“this”。例如:
和它旁边的那一行。是打印测试文件的第2行连接到db
?
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;
var DB = require('./db');
var myDB = new DB();
myDB.getCollection('myCollection'); // <--- error: Cannot call method 'collection' of null
this.db = new mongodb.Db('myDB', server);