Building an application with a combination of both using express and MongoDB is quite common nowadays.
When working with JavaScript web-based applications, one will normally here of the term MERN stack:
- MERN stack refers to a collection of JavaScript-based technologies to develop web applications.
- MERN is an acronym for MongoDB, ExpressJS, AngularJS, and Node.js.
Hence, it’s always good to understand how Node.js and MongoDB work together to deliver applications that interact with backend databases.
Let’s look at a simple example of how we can use “express” and “MongoDB” together. Our example will make use of the same Employee collection in the MongoDB EmployeeDB database.
_We will now incorporate Express to display the data on our web page when it is requested by the user. When our application runs on Node.js, one might need to browse to the URL http://localhost:3000/Employeeid.
When the page is launched, all the employee id in the Employee collection will be displayed. So let’s see the code snippet in sections that will allow us to achieve this.
Step 1) Define all the libraries which need to be used in our application, which in our case is
both the MongoDB and express library.
Code Explanation:
- We are defining our ‘express’ library, which will be used in our application.
- We are defining our ‘express’ library, which will be used in our application for connecting to our MongoDB database.
- Here we are defining the URL of our database to connect to.
- Finally, we are defining a string that will be used to store our collection of employee id which need to be displayed in the browser later on.
Step 2) In this step, we are now going to get all of the records in our ‘Employee’ collection and
work with them accordingly.
Code Explanation:
- We are creating a route to our application called ‘Employeeid.’ So whenever anybody browses to http://localhost:3000/Employeeid of our application, the code snippet defined for this route will be executed.
- Here we are getting all of the records in our ‘Employee’ collection through the db.collection(‘Employee’).find() command. We are then assigning this collection to a variable called cursor. Using this cursor variable, we will be able to browse through all of
the records of the collection.
- We are now using the cursor.each() function to navigate through all of the records of our collection. For each record, we are going to define a code snippet on what to do when each record is accessed.
- Finally, if the record returned is not null, we are taking the employee via the command “item.Employeeid”. The rest of the code is just to construct a proper HTML code that will allow our results to be displayed properly in the browser.
Step 3) In this step, we are going to send our output to the web page and make our
application listens on a particular port.
Code Explanation:
- Here we are sending the entire content which was constructed in the earlier step to our web page. The ‘res’ parameter allows us to send content to our web page as a response.
- We are making our entire Node.js application listen on port 3000.
OUTPUT:
From the output,
It clearly shows that all of the employeeid’s in the Employee collection were retrieved.
This is because we use the MongoDB driver to connect to the database and retrieve all the Employee records and subsequently used “express” to display the records.
Here is the code for your reference
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
var str = "";
app.route('/Employeeid').get(function(req, res)
{
MongoClient.connect(url, function(err, db) {
var cursor = db.collection('Employee').find();
//noinspection JSDeprecatedSymbols
cursor.each(function(err, item) {
if (item != null) {
str = str + " Employee id " + item.Employeeid + "";
}
});
res.send(str);
db.close();
});
});
var server = app.listen(3000, function() {})
Note:
cursor.each may be deprecated based on the version of your MongoDB driver. You can
append //noinspection JSDeprecatedSymbols before cursor.each to circumvent the issue.
Alternatively, you can use forEach. Below is the sample code using forEach
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
var str = "";
app.route('/Employeeid').get(function(req, res) {
MongoClient.connect(url, function(err, db) {
var collection = db.collection('Employee');
var cursor = collection.find({});
str = "";
cursor.forEach(function(item) {
if (item != null) {
str = str + " Employee id " + item.Employeeid + "";
}
}, function(err) {
res.send(str);
db.close();
}
);
});
});
var server = app.listen(8080, function() {});
Summary:
Node.js is used in conjunction with NoSQL databases to build a lot of modern days web applications. Some of the common databases used are MySQL and MongoDB.
One of the common modules used for working with MongoDB databases is a module called ‘MongoDB.’ This module is installed via the Node package manager.
With the MongoDB module, it’s possible to query for records in a collection and perform the normal update, delete and insert operations.
Finally, one of the modern practices is to use the express framework along with MongoDB to deliver modern-day applications. The Express framework can make use of the data returned by the MongoDB driver and display the data to the user on the web page accordingly.