[英]TypeError: Cannot read property 'findAll' of undefined - Node.js + Postgresql
[英]Node.js and mongodb: TypeError: Cannot read property 'findAll' of undefined
我正在使用JavaScript( https://www.raywenderlich.com/2663-how-to-write-a-simple-node-js-mongodb-web-service-for-an-ios)遵循此Node.js和mongodb教程-app )。
我從終端運行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中的預期輸出應類似於本教程中說明的以下內容:
誰能告訴我哪里出問題了? 我正在使用mongodb 1.3.23版(就像本教程一樣)
Node js異步運行。 在您的情況下,我認為“ collectionDriver
”在使用之前沒有初始化。 嘗試使用Promise使它們同步。 在調用.findAll(...)之前,請確保已初始化“ collectionDriver
”。
希望我的回答對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.