Reputation: 233
I am following this Node.js and mongodb tutorial with javascript (https://www.raywenderlich.com/2663-how-to-write-a-simple-node-js-mongodb-web-service-for-an-ios-app).
I am getting an error when I run node and mongodb from terminal then go to http://localhost:3000/items. The error appears to be in this block of code:
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
}
}
});
});
In the code above this, I set the collectiondriver database:
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
});
The error when I go to localhost:3000/items is:
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)
Line 32 in index.js starts with "collectionDriver.findAll". What is the reason findAll() is undefined?
The expected output of the page in localhost:3000/items should look like the following as explained in the tutorial:
Can anyone please tell me what is wrong? I am using mongodb version 1.3.23 (like the tutorial uses)
Upvotes: 0
Views: 181
Reputation: 71
Node js runs asynchronously. In your case, I think the "collectionDriver
" is not getting initialized before you use it. Try to use promises to make them synchronized. Make sure your "collectionDriver
" is initialized before you call .findAll(...).
I hope my answer helps.
Upvotes: 1