0

I'm attempting to create a Rest API using Node.js, Express, and MongoDB. I am currently running on my local host :3000. When I try to restart and run the server I am using the route http://localhost:3000/drinks

I use Postman to send HTTP requests. https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

While trying to send the route above, it does not retrieve any information. It just continues load.

This is my first time creating a REST API and I'm not sure why it isn't retrieving the data. Attached below is my code. Thanks in advance!

server.js

var express = require('express'),
    drink = require('./routes/drinks');

var app = express();

app.configure(function () {
        app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
        app.use(express.bodyParser());
    });

app.get('/drinks', drink.findAll);
app.get('/drinks/:id', drink.findById);                                                                       

app.listen(3000);
console.log('Listening on port 3000...');

drinks.js

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('drinkdb', server);

db.open(function(err, db) {
        if(!err) {
            console.log("Connected to 'drinkdb' database");
            db.collection('drinks', {strict:true}, function(err, collection) {
                    if (err) {
                        console.log("The 'drinks' collection doesn't exist. Creating it with sample data...");
                        populateDB();
                    }
                });
        }
    });

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving drink: ' + id);
    db.collection('drinks', function(err, collection) {
            collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
                    res.send(item);
                });
        });
};

exports.findAll = function(req, res) {
    db.collection('drinks', function(err, collection) {
            collection.find().toArray(function(err, drinks) {
                    res.send(drinks);
                });
        });
};
/*---------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.                   
// You'd typically not find this code in a real-life app, since the database would already exist.                     
var populateDB = function() {

    var drinks = [
    {
            id: "1",
            name: "Margarita",
            ingredients: ["Tequila","Lime juice","Triple Sec","Lime","Salt","Ice"],
            measurements: ["2 oz","1 oz","1 oz","1","optional","optional"],
            directions: "Shake the other ingredients with ice, then carefully pour into the glass. Served: On the roc\
ks; poured over ice. Optional: Salt the rim of the glass by rubbing lime on it so it sticks."
    },
   {
            id: "2",
            name: "Strawberry Margarita",
            ingredients: ["Tequila", "Lime juice","Triple Sec","Strawberries","Lime","Salt", "Ice"],
            measurements: ["2 oz","1 oz", "1 oz", "3 1/2 cups", "1", "optional", "optional"],
            directions: "Combine strawberries, ice, tequila, lime juice, and triple sec in a blender, and process unt\
il the mixture is smooth. Carefully pour into the glass. Served: On the rocks; poured over ice. Optional: Salt the ri\
m of the glass by rubbing lime on it so it sticks."
   }];

    db.collection('drinks', function(err, collection) {
            collection.insert(drinks, {safe:true}, function(err, result) {});
        });
};

Warnings are:

express deprecated app.configure: Check app.get('env') in an if statement server.js:6:5
connect deprecated multipart: use parser (multiparty, busboy, formidable) npm module instead node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:56:20
connect deprecated limit: Restrict request size at location of read node_modules/express/node_modules/connect/lib/middleware/multipart.js:86:15
8
  • add some console.log() statements to your code to find out how far it is getting. As a starting point - in your findAll function and possibly even in the call-back for your app.get('/drinks',..) Commented Dec 23, 2015 at 23:46
  • Are you sure that your db is started ? If yes, is it binded to 27017 ? Commented Dec 23, 2015 at 23:51
  • Ok I did that and it is having problems with line collection.find().toArray(function(err, drinks) {res.send(drinks);}); @Tim Commented Dec 23, 2015 at 23:52
  • check if an error is being returned: if (err){ console.error('err:',err);} Commented Dec 23, 2015 at 23:54
  • I added that line of code and no error was returned @Tim Commented Dec 23, 2015 at 23:55

2 Answers 2

1

I think Ashley is on the right track. But to make it more clear where the problem is happening try using this as a guide: http://expressjs.com/en/guide/routing.html

app.get('/drinks', function (req, res) {
  drink.findAll(req, res);
});

Then you can add logging in between this call and in your findAll function.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Tim, thought my method would word but perhaps not. I'll update my answer.
0

Your models (drinks.js) accept two parameters (req & res) but on your route you don't pass in any parameters.

Try the following:

app.get('/drinks', function(req, res) {
    drink.findAll(req, res);
});

app.get('/drinks/:id', function(req, res){
    drink.findById(req, res);
});

Alternatively, you could achieve the same with a callback based structure:

server.js

...

app.get('/drinks', function(req, res) {
    drink.findAll(function(err, drinks){
        res.send(drinks)
    });
});

...

drinks.js

...

exports.findAll = function(callback) {
    db.collection('drinks', function(err, collection) {
            collection.find().toArray(function(err, drinks) {
                    callback(err, drinks)
                });
        });
};

(error handling required) ...

1 Comment

I add those lines and ReferenceError: req is not defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.