简体   繁体   English

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

[英]Error in connecting database (mongo and nodejs)

I want build a class for wrapping database connection.我想构建一个 class 来包装数据库连接。 This is my code ('db.js' file):这是我的代码('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;

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

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".您在“db”前面缺少“this”。 eg:例如:

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

And the line next to it.和它旁边的线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM