TypeError:无法读取未定义nodejs&的属性'find'。 mongoclient

时间:2017-11-28 16:09:52

标签: javascript json node.js mongodb

我正在尝试从我的meteor mongo数据库获取信息并在我的网页上将其显示为json,但是我收到错误TypeError: Cannot read property 'find' of undefined而我不知道为什么。

var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:3001", function(err, database) {
if(err) //console.log(err);
console.log(database);
  db = database;
  // Start the application after the database connection is ready
  app.listen(3001);
  console.log("Listening on port 3000");
});

// middleware to use for all requests
router.use(function (req, res, next) {
  // do logging
  //console.log('Something is happening.');
  next(); // make sure we go to the next routes and don't stop here
});
router.route('/subscribers')
  app.get("/api/subscribers", function (req, res) {

    db.subs.find({}, function(err, docs) {
      docs.each(function(err, doc) {
        if(doc) {
          res.json(doc);
        }
        else {
          res.end();
        }

      });
    });
  });

2 个答案:

答案 0 :(得分:0)

你的问题就在这里:

db.subs.find({}, function(err, docs) {

subs个对象中没有db属性。检查以确保数据库正确加载并具有subs属性。如果您需要考虑没有subs属性的情况,您可以执行以下操作:

  app.get("/api/subscribers", function (req, res) {
    if (db.subs) {
      db.subs.find({}, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            res.json(doc);
          }
          else {
            res.end();
          }

        });
      });
     }
  });

答案 1 :(得分:0)

确保static bool SetContainsString(string searchString, HashSet<string> setOfStrings) { for (int i = 0; i < searchString.Length; i++) { var segment = searchString.Substring(0, i + 1); if (setOfStrings.Contains(segment)) { var remainingSegment = searchString.Substring(segment.Length); if (remainingSegment == "") return true; return SetContainsString(remainingSegment, setOfStrings); } } return false; } 存在。这是因为subs未在行中定义:

subs