Node js is one of the best parts of javascript development. It gives javascript developers the power to write the backend part with javascript. However, Node js is little bit advanced and not much beginner friendly so express gains a lot much popularity. Express is a node js framework and it’s much easy to use. MongoDB is one of the most popular database systems. Unlike others its store’s data as a JSON object. The term MEAN stack is much popular nowadays. MEAN stands for MongoDB, Express, Angular and Node Js. The term is related to full stack development. In this post, I will explain the basics of node js MongoDB and express. So let’s know each of them in brief at first.

Node js

node jsNode Js is one of the most popular choices of back-end developers. Unlike PHP which requires a web server installed you can create your own server with Node Js in seconds. Its really lightweight and works from command line. One can create highly scalable apps and API’s easily with Node Js. It’s asynchronous so you will always have a callback for every event it runs. LinkedIn, Netflix and PayPal like huge companies are using Node Js.

MongoDB

mongodbMongoDB is one of the greatest inventions in the databases world. Its lighter, faster and much flexible than its competitors. It’s created with C programming language which gives a great performance. In addition to all MongoDB is a No SQL database. So you will never have to worry about complicated SQL anymore. On the other hand, it stores data as a JSON object. So if you are comfortable with JSON then it will surely give a boost.

Express Js

express jsExpress Js is a lightweight, fast, easy to use Node Js framework. It makes the task much easier to develop hugely complicated apps with Node Js. You can even install it easily with a simple command. Just run the command and it will automatically install Express Js and its dependencies. Express provides various middlewares that come handy in many situations.

Finally, I think you got to know what you are going to learn today. So let’s move on and create our Node Js MongoDB and Express project.

Node JS MongoDB and Express

First of all, I hope you guys have installed MongoDB and Node Js. So I am skipping it and moving to the main part.

Install Express and create a simple server

Create a folder and name it whatever you like. Now go inside that folder and open the command prompt. Now type npm init and run the command. It will create a package.json file for your project. You can add a name, description, version and many other things to the app. Once your package.json is ready run the following commands.

npm install express –save it will automatically download and install express with its dependencies. We will also need a body parser so let’s install it. npm install body-parser –save it will do the same job i.e download and install. Now open the folder in a text editor and look for the index.js file. Open the file and add follow the codes.

var express = require('express');
var bodyParser = require('body-parser');

First of all its necessary to create the required variables. I am not using the ES6 syntax because many people are not familiar with it.

var app = express();

The above code will call the express constructor and after that, we can use any specific features of express.

app.get('/', function(req, res) {
	res.send('Hello World');
});

So now we are creating a get request. The get request method has 2 parameters. First one is the requested URL and the second one is the callback function. Look what the URL is just contained a / because we are requesting the home page. After that inside the callback function, we are using the send method to show a message. The two parameters of callback function are used for handling request and response.

app.listen(3000, function() {
	console.log('Server started on port 3000');
});

Finally, listen method will start the server on our specified port. So now run node index.js and open a browser then go to localhost:3000 you will see it’s displaying Hello World.

Setup view engine and paths

There are many good view engines or templating engines are available for Node JsEJS is one of the best among them. So let’s install EJS first and then start to code.

npm install ejs –save the command will download and install EJS with its dependencies. Now open your index.js file and add a path variable.

var path = require('path');

Ok, now we have to setup our view engine to work on our project. Create a folder called views inside the current directory. The folder views will contain all the ejs files.

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

Now we have to setup our body parser middleware. It parses incoming request bodies in a middleware before your handlers, available under the req.bodyproperty.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

Finally, we have to setup the static path as follows. Create a folder called public inside the current directory and follow the given code.

app.use(express.static(path.join(__dirname, 'public')));

So our template engine and paths setup are done. Now let’s create our template.

Create templates

Go inside the views directory and create a file called index.ejs. Now open the file in a text editor and follow the code.

I hope you guys are familiar with HTML5 structures. So write the HTML structure first because I will show only what you have to put inside body element.

<h1><%= title %></h1>

Now go back to your index.js file and change the code inside of the get method.

app.get('/', function(req, res) {
	res.render('index', {
		title: 'My app'
	});
});

The render method is used to render a template. Ths method takes 2 arguments one is template name other is a list of data we want to use in that template.

Now run the app and check it in a browser. You will see the title we have specified.

MongoDB database setup and retrieve values

First of all, open the mongo shell and create a new database called peoples. It’s the last section of our Node js MongoDB and Express project.

use peoples will create a database called peoples. Now insert records into the database as follows.

db.users.insert({name:'Subham Mitra',age:20})

Use square brackets outside of curly braces to insert multiple rows at a time. Now go back to your project directory and run npm install mongojs –save. Mongo Js is most simple and easy to use, a library to work with Mongo and Node. So now we have to put it in a variable to use its features. Open the index.js file and add those vars.

var mongojs = require('mongojs');
var db = mongojs('peoples', ['users']);

The mongojs method has 2 arguments first one is the database name or connection string other one is the list of collections. Now in order to retrieve the values from the database, we have to modify our get method.

db.users.find(function (err, docs) {
	res.render('index', {
		title: 'My app',
		users: docs
	});
});

The find method is used to retrieve values from the database. Now we can use users in our index.ejs template to display the data.

<ul>
<% users.forEach(function(user) { %>
	<li>Name : <%= user.name %></li>
	<li>Age: <%= user.age %></li>
<% }) %>
</ul>

So put the above code after the h1 tag. It’s applying a function to every users object and user is the current instance of the object. So now you know how to use Node Js MongoDB and Express together.

Add values to the MongoDB database

So now we know how to retrieve values now let’s see how to add values. First of all, open the index.ejs and create a form as below.

<form method="post" action="/peoples/add">
	<label>Name</label>
	<input type="text" name="name">
	<br><br>
	<label>Age</label>
	<input type="text" name="age">
	<br><br>
	<input type="submit" value="submit">
</form>

Now we have to create a post request with the specified URL of the action attribute. So open your index.js file and add the following code. It will add a new post request into our Node Js MongoDB and Express project.

app.post('/peoples/add', function(req, res) {
	var newPeople = {
		name: req.body.name,
		age: req.body.age
	}
	db.users.insert(newPeople, function(err, result) {
		if(err) {
			console.log(err);
		}
		res.redirect('/');
	});
});

So in the above code, the var newPeople is holding the object values. Here you can see the use of body parser. After that, I have added an insert method which is storing the values of newPeople. If the query fails with an error then it will be displayed in the console. Otherwise, it will return to the home page with an updated table.

So you can apply many different queries to the database by using mongo js. I have just shown how to retrieve and add data now you can follow mongo js docs to play with other queries.

So, guys, I hope with this project you have learned how to use Node js MongoDB and Express altogether.


subham

A coder who loves to solve real-world problems through coding.

Leave a Reply

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

Related Posts

Books

Best JavaScript book for absolute beginners

JavaScript is one of the most popular and widely used programming languages. Basically, its used in front-end development but it’s not limited up to that. There are many great frameworks or libraries available to do Read more…

Javascript

Vue Js hybrid app development with Framework 7

Hybrid app development is growing stronger day by day. It’s much simpler and easy to learn than native app development. Basically, hybrid app frameworks give the ability to develop multi-platform apps to front-end developers. With Read more…

Javascript

Vue js tutorial for absolute beginners

Vue js is one of the most loving javascript frameworks among developers. It comes with many great features that make it into the top frameworks list. The most amazing features of Vue is its lightweight Read more…