TypeError:无法读取null的属性“ collection”

时间:2018-06-21 09:29:40

标签: node.js mongodb express

我基本上是试图从节点js应用程序访问mongodb集合。我建立了连接,但是在收集时却出现此错误。这是我的.js文件     var dbconn = require('../ data / dbconnection.js');     var ObjectId = require('mongodb')。ObjectID;

var hotelData = require('../data/hotel-data.json');

module.exports.hotelsGetAll = function(req, res) {

  var db = dbconn.get();

  // console.log("db", db);

  console.log('GET the hotels');
  console.log(req.query);

  var offset = 0;
  var count = 5;

  var collection = db.collection('hotels');

  if (req.query && req.query.offset) {
    offset = parseInt(req.query.offset, 10);
  }

  if (req.query && req.query.count) {
    count = parseInt(req.query.count, 10);
  }

  collection
    .find()
    .skip(offset)
    .limit(count)
    .toArray(function(err, docs) {
      console.log("Found hotels", docs.length);
      res
        .status(200)
        .json(docs);
  });

};

module.exports.hotelsGetOne = function(req, res) {
  var db = dbconn.get();
  var id = req.params.hotelId;
  var collection = db.collection('hotels');
  console.log('GET hotelId', id);

  collection
    .findOne({
      _id : ObjectId(id)
    }, function(err, doc) {
      res
        .status(200)
        .json(doc);
  });

};

更新:我正在使用MongoDB 3.0.10版,我的connection.js文件如下

var MongoClient = require('mongodb').MongoClient;
var dburl = 'mongodb://localhost:27017';

var _connection = null;

var open = function() {
    MongoClient.connect(dburl, function(err , db) {
        if(err){
            console.log("DB connection failed");
            return;
        }
        _connection = db.db('meanhotels');
        console.log("DB connection open",db);

    });
};

var get = function() {
    return _connection;
};

module.exports = {
    open : open,
    get : get
}

1 个答案:

答案 0 :(得分:1)

似乎您的dbconn.get()返回null。检查您的数据库连接字符串,然后尝试通过其他客户端(CLI工具,mongo3t)与之连接