Friday, February 3, 2017

Express With MongoDB - Quick start

Let's access MongoDB from Nodejs using Express. 

What is Express? 
As per Express site, it's a minimal and flexible Node.js web application framework that provides a robust set of features for the web and mobile applications.

Features
·         Robust routing
·         Focus on high performance
·         Super-high test coverage
·         HTTP helpers (redirection, caching, etc)
·         View system supporting 14+ template engines
·         Content negotiation
·         Executable for generating applications quickly

Great.Lets start. (Assumed you have Nodejs and MongoDB installed, if not ,check Nodejs MongoDb)

Create a folder and run following command on your terminal-

 > npm init

It will ask you few questions (Like- Name for the project, author, version). For now, you can keep all the default values. This will give you your package.json inside the same folder.

Greate execute this now-

> npm install --save express
mongoose morgan body-parser

So here, we actually installed Express along with mongoose which is a Node.js library that provides MongoDB object mapping similar to ORM with a familiar interface within Node.js and Morgan which is basically used for logging request details. And body-parser parses incoming request bodies in a middleware before your handlers, available under the req.body property.

Now you should see a folder named node_modules inside your current folder. Inside node_modules all your installed node packages reside. We are now ready to go further.

Let's create a file and name it server.js. Put the following code and save it.

var express = require('express'); // load express module in your project

var morgan = require('morgan'); // load morgan module 

var mongoose = require('mongoose'); //load mongoose module 

var bodyParser = require('body-parser'); // load body-parser module 

var app = express(); //init express
var port = process.env.PORT || 6064; //allocate the port for your server
app.use(express.static('./public')); // set folder for public items , such as - image , css, html, client side js
app.use(morgan('dev')); // init morgan for logging request details
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

mongoose.connect('mongodb://localhost/mongodbtest'); // mongodb connection

routesetup(app);// set your route details with path and its handlers 
app.listen(port);// start your server
console.log("App listening on port " + port); 


function routesetup(app) { // function for route setup
   app.use( function (req, res, next) {  // will be executed for all request
        console.log(req.url);
        next();
    });
    app.use( function (err, req, res, next) { // will be executed for all error
        console.log(err);
        next();
    });    
// REST API to access from client side js--> 
    app.get('/api/todos', function (req, res) { // get method route
       todo.find(function (err, todos) { // used mongoose model to get data
            if (err) {
                res.send(err);
            }

            res.json(todos);
        });
    });
app.post('/api/todos', function (req, res) { //post method route
 var td = new todo({
 val: req.body.val
        });

        td.save(function (err, td) { // use mongoose model to dave data
            if (err) {
                return res.status(500).json({
                    message: 'Error when creating todo',
                    error: err
                });
            }
            return res.status(201).json(todo);
        });
});
    app.get('*', function (req, res) { // get method for html
        //throw new Error('err');
        res.sendFile(__dirname + '/public/index.html');
    });
}

var todo = mongoose.model('Todo', { //mongoose model
    val: {
        type: String,
        default: ''
    }
});

Now create a folder public and inside it create a file index.html  and add following -

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#btn").click(function () {
            $.post("/api/todos",
                {
                    val: $("#txttask").val()
                },
                function (data, status) {
                    console.log("Data: " + data + "\nStatus: " + status);
                });

            $("#txttask").val('');
            getData();
        });
        function getData() {
            $.get("/api/todos", function (data, status) {
                var listVal = "";
                $.each(data, function (index, val) {
                    listVal += val.val + "<br>";
                })
                $("#listtask").html(listVal);
            });
        }
        getData();
    });
</script>
</head>

<body>
    <div>
        <b>Express Running</b></div>
    <div>
        <label> Task:</label><input type="text" id="txttask" /><button id="btn">Save</button>
    </div>
    <div>
        <b>Task List</b>
    </div>
    <div id="listtask"></div>
</body>

</html>

Save both the files.

Note: Please read all the inline comments carefully for better understanding.

Greate . Now we are ready to run our first Express application with MongoDB.

Run you mongoDB, before going further.(go to your mongo installation folder and then ./bin folder using a new terminal window)

mongod --directoryperdb --dbpath <folder path>


To Run the application, execute following in your terminal-

> node server.js

Now Try to open - http://localhost:6064/

If you have done it properly, you should see your HTML page with heading Express Running. Using the api created in server.js you can save and see the saved list of items in the page.

That's it.

Feel free to ask if you have any queries. 



Post a Comment