Node.js和mongodb:TypeError:无法读取未定义的属性'findAll'

时间:2019-06-04 20:30:04

标签: javascript node.js mongodb

我正在使用JavaScript(https://www.raywenderlich.com/2663-how-to-write-a-simple-node-js-mongodb-web-service-for-an-ios-app)遵循本Node.js和mongodb教程。

我从终端运行node和mongodb时,出现错误,然后转到http://localhost:3000/items。错误似乎在以下代码块中:

app.get('/:collection', function(req, res) { //A
   var params = req.params; //B
   collectionDriver.findAll(req.params.collection, function(error, objs) { //C
          if (error) { res.send(400, error); } //D
          else {
              if (req.accepts('html')) { //E
                  res.render('data',{objects: objs, collection: req.params.collection}); //F
              } else {
              res.set('Content-Type','application/json'); //G
                  res.send(200, objs); //H
              }
         }
    });
});

在上面的代码中,我设置了collectiondriver数据库:

var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort)); //B
mongoClient.open(function(err, mongoClient) { //C
  if (!mongoClient) {
      console.error("Error! Exiting... Must start MongoDB first");
      process.exit(1); //D
  }
  var db = mongoClient.db("MyDatabase");  //E
  collectionDriver = new CollectionDriver(db); //F
});

我转到localhost:3000 / items时的错误是:

TypeError: Cannot read property 'findAll' of undefined
    at /Users/username/Documents/NodeTutorial/index.js:32:21
    at Layer.handle [as handle_request] (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/layer.js:95:5)
    at /Users/username/Documents/NodeTutorial/node_modules/express/lib/router/index.js:281:22
    at param (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/index.js:354:14)
    at param (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/index.js:410:3)
    at next (/Users/username/Documents/NodeTutorial/node_modules/express/lib/router/index.js:275:10)

index.js中的第32行以“ collectionDriver.findAll”开头。 findAll()未定义的原因是什么?

在localhost:3000 / items中页面的预期输出应类似于本教程中说明的以下内容:

enter image description here

任何人都可以告诉我出什么事了吗?我正在使用mongodb 1.3.23版(就像本教程一样)

1 个答案:

答案 0 :(得分:1)

Node js异步运行。就您而言,我认为“ collectionDriver”在使用之前没有初始化。尝试使用promises使它们同步。在调用.findAll(...)之前,请确保已初始化“ collectionDriver”。

希望我的回答有帮助。