【发布时间】:2019-10-20 09:37:12
【问题描述】:
我正在使用 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 中页面的预期输出应如下所示,如教程中所述:
谁能告诉我什么是错的?我使用的是 mongodb 1.3.23 版(就像教程使用的一样)
【问题讨论】:
-
你添加打开数据库连接的代码了吗?该错误表明未设置
collectionDriver。在您链接的文章中,有一些设置代码来初始化此值。这应该超出您在此处粘贴的代码。 -
@AustinGreco 我把代码贴在我设置的地方。
标签: javascript node.js mongodb