Build an Application in NodeJS, Express and MongoDB - Part 2

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

This article is the second in our two-part series explaining how to build an application using NodeJS, Express and MongoDB. In our first article, we reviewed some of the essential steps needed to get started in the project: installing, setting up and configuring everything you’ll need. We also reviewed some important code used in the application. We’ll pick up where we left off in this second installment and go over the rest of the tasks required to complete our application.

Prerequisites

Before proceeding with this article, make sure you’ve installed both NodeJS and NPM as described in the previous article. Be sure you’ve also followed along with the steps detailed in the first article and reviewed the sample code.

Create an Express server for the routing of the Node application

In this section, we’ll use the NPM package manager to install the Express module and a few others:

1
npm install --save express@4.17.1 express-handlebars@3.1.0 body-parser@1.19.0

In the same directory, create a folder named controllers which will contain a file named studentController.js. The code we add to this file will create a constant variable for the Express server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Create a constant variable for the express server
const express = require('express');
var router = express.Router();

// Handle the Get request from the server
router.get('/', (req, res) => {
res.render("student/addOrEdit",{
viewTitle: "Insert Student Information"
});
});

// Create a method post to get the form action of the express-handlebars
router.post('/', (req,res)=> {
console.log(req.body)
})

// Export to call the function in the root file.
module.exports = router;

After creating the controllers that are used for the routing of the Express server, we will now set the views. These will be used to get access and create our information from MongoDB:

We’ll need to create a views folder containing a file named addOrEdit.hbs. We’ll add the following code to the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{{viewTitle}}


<form action="/student" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{student._id}}">
<label>Student Name</label>
<input type="text" class="form-control" name="stud_name" placeholder="Student Fullname" value="{{student.stud_name}}">

{{student.titleError}}



<label>Email Address</label>
<input type="text" class="form-control" name="email_add" placeholder="Email Address" value="{{student.email_add}}">

{{student.email_addError}}




<label>Contact Number</label>
<input type="text" class="form-control" name="contact" placeholder="Contact Number" value="{{student.contact}}">

<label>Country</label>
<input type="text" class="form-control" name="country" placeholder="Country" value="{{student.country}}">


<button type="submit" class="btn btn-info">
Submit</button>
{{!--
View All
--}}

</form>

Our final task is to configure the root file so that we can create the path for the Express server and use the middleware to get our results in JSON format. Here’s what we need to do:

app.js

  • We begin by creating the constant variable for the root file.
1
2
3
4
5
6
7
8
require('./models/db');

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');

const bookController = require('./controllers/studentController');
  • Next, we add and configure the variable app to submit a JSON HTTP POST request.
1
2
3
4
5
var app = express();
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
  • We can then set our Express handlebars.
1
2
3
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainlayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');
  • Last but not least, we’ll specify the port that will listen on the client server on the web host.
1
2
3
4
5
6
7
8
app.listen(5050, () => {

console.log('Now starting at port: 5050');

});

// Importing the studentController for the routing
app.use('/student', studentController);

To run the application, simply use the command node app.js. The result should look like this:

1
2
Now starting at port: 5050
Successfully Connected in MongoDB

Enter the URL localhost:5050/student in your browser’s address bar; then, fill out the form.

You’ll notice that in the data you entered in the form will be posted to your terminal. This occurs because the application returns the request from the server as a parser in JSON data.

1
2
3
4
5
{ _id: '',
stud_name: 'Aris Mahone',
email_add: 'arismahone@gmail.com',
contact: '65632956',
country: 'AU' }

Because the browser is still loading, it provides more and more information in the terminal until the application is stopped.

Conclusion

Building an application using NodJS, Express and MongoDB is a process that involves a number of different tasks. It’s important to understand each step of the process to make sure that the application is built and configured correctly. In this article, we picked up where we left off after our first installment, and we reviewed the rest of the code needed to complete our application. If you’ve followed along with both articles in the series, you’ll be prepared to build your own Node application that interacts with a MongoDB database.

Just the code

If you’d like to use our sample code to get started with your own NodeJS application, you can copy the code shown below:

studentController.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const express = require('express');
var router = express.Router();

router.get('/', (req, res) => {
res.render("student/addOrEdit",{
viewTitle: "Insert Student Information"
});
});

router.post('/', (req,res)=> {
console.log(req.body)
})


module.exports = router;

addOrEdit.hbs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{{viewTitle}}


<form action="/student" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{student._id}}">
<label>Student Name</label>
<input type="text" class="form-control" name="stud_name" placeholder="Student Fullname" value="{{student.stud_name}}">

{{student.titleError}}



<label>Email Address</label>
<input type="text" class="form-control" name="email_add" placeholder="Email Address" value="{{student.email_add}}">

{{student.email_addError}}




<label>Contact Number</label>
<input type="text" class="form-control" name="contact" placeholder="Contact Number" value="{{student.contact}}">

<label>Country</label>
<input type="text" class="form-control" name="country" placeholder="Country" value="{{student.country}}">


<button type="submit" class="btn btn-info">
Submit</button>
{{!--
View All
--}}

</form>

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require('./models/db');

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');

const studentController = require('./controllers/studentController');


var app = express();
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainlayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');

app.listen(5050, () => {
console.log('Now starting at port: 5050');
});

app.use('/student', studentController);

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.