Create Node Server with Express & MongoDB [part-2]

If you miss the previous post, you can check it from here Create Node Server with Express & MongoDB

Step 5: Verify mongodb connection with a new collection (Save & Find)

Lets create a db model file under app/models. Lets called the file name bear.js and put the following content into the file:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var BearSchema = new Schema({
    name : String
});

module.exports = mongoose.model('Bear', BearSchema);

To use this model, we need to include it into the server.js file. But our purpose is to save some data into mongodb server and query the content. For that we need to define some ROUTE. To do that, let's create a file called route.js under app/config folder and put the following content into the file:

var express = require('express'),
    Bear = require('../../app/models/bear');

/**
 * To insert data on POST method
 */
router.post('/bears', function (req, res){
    var bear = new Bear();

    bear.name = req.body.name;
    bear.save(function (err){
        if (err) res.send(err);
        res.json({message: 'Successfully created'});
    });
});

/**
 * To get all data on GET method
 */
router.get('/bears', function(req, res) {
    Bear.find(function(err, bears){
        if (err) res.send(err);
        res.json(bears);
    });
});


module.exports = router;

Now to access the url, we need to include the route.js file in server.js file in the following way:

.......................................
router = require('./app/config/route'),
.......................................

again, to maintain better REST url, we add a prefix 'api' to each route for the app. To do that add the following line:

............................
app.use('/api', router)
............................

Now you can access the url like this:

//To Save data
POST http://localhost:8080/api/bears

//To get all data
GET http://localhost:8080/api/bears

Lets try to access the url using postman chrome extension:

First add a data with POST url:

screen-shot-2016-10-16-at-8-52-22-pm

Now get the data using GET url:

screen-shot-2016-10-16-at-8-52-43-pm

Leave a Reply

Your email address will not be published. Required fields are marked *