【问题标题】:TypeError: Cannot read property 'find' of undefined nodejs & mongoclientTypeError:无法读取未定义 nodejs 和 mongoclient 的属性“查找”
【发布时间】:2017-11-28 16:09:52
【问题描述】:

我正在尝试从我的流星 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();
        }

      });
    });
  });

【问题讨论】:

  • 检查您的数据库是否已连接,因为您的 app.port ant DB 端口正在同一端口上运行
  • 根据文档,您应该在 db 对象上调用 collection 方法来访问集合。即db.collection('subs').find(...)
  • 感谢@AhmadBaktashHayeri 是问题所在^^

标签: javascript json node.js mongodb


【解决方案1】:

你的问题就在这里:

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

db 对象中没有 subs 属性。检查以确保您的数据库正确加载并具有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();
          }

        });
      });
     }
  });

【讨论】:

  • subs 是我的收藏,所以我应该怎么做才能在我的收藏中找到名为 subs 的内容?
  • 看起来你正在这样做,前提是subs 存在。问题是subs 不存在。 subsundefined
【解决方案2】:

确保subs 存在。这是因为subs 在以下行未定义:

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

【讨论】:

    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 2022-09-23
    • 2022-11-29
    • 2017-08-30
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多