NodeJS With MongoDB

This is the article of how to install Node.js with Express.js framework using MongoDB in ubuntu.
Here we will use Mongoose.js module and “ejs” that comes with Express.js framework.
NodeJS is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable
network applications. Latest version of nodejs is maintaining by its official website.


1.Node js installation


To install node js and NPM (Node package Module) on Ubuntu run below command:-

sudo apt-get install curl python-software-properties

curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash –

sudo apt-get install nodejs

After installing nodejs check your installed nodejs version using below command:-

  1. node -v

Now we can install NPM using below command :-

  1. sudo apt install npm

To check NPM version

npm -v

2. Create A Project


Now we are creating a web application using Express.js project generator that works in
command line using below command

npm init

To install express globally use below command

  1. sudo npm install express-generator -g

OR

  1. npm install express –save
  2. express –view=ejs

To install MongoDB use below command

  1. sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv
    2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
    echo “deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu

xenial/mongodb-org/3.6 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-
org-3.6.list

  1. sudo apt-get update
  2. sudo apt-get install -y mongodb-org
  3. sudo apt-get install -y mongodb-org=3.6.0 mongodb-org-server=3.6.0 mongodb-
    org-shell=3.6.0 mongodb-org-mongos=3.6.0 mongodb-org-tools=3.6.0

To check mongoDB installed and start the mongoDB service use below command

  1. sudo service mongod start
    Now we can check service is start or not use below command:
  2. sudo service mongod status
    To stop mongoDB service
  3. sudo service mongod stop
    Now we can install mongoDb tool to manage databse and databse structure i’m using ROBO
    3T tool. To install robo3t use below command:
  4. sudo snap install robo3t-snap
    Now that command will create a project folder called “node-demo” with view template using “ejs”
    extension.

Next, go to newly created project folder then install node modules.

  1. express node-demo –view=ejs
  2. cd node-demo && npm install
    Next, we are installing Mongoose.js module by this command.
  3. npm install mongoose –save

Now, open and edit app.js from the root of the project folder. And add Mongoose.js to ‘require’
and call connection to MongoDB.

var mongoose = require(‘mongoose’);
mongoose.Promise = global.Promise;
mongoose.connect(‘mongodb://localhost/product’)
.then(() => console.log(‘connection succesful’))
.catch((err) => console.error(err));

Now we have to test connection to database server. First start the node server using below
command.

  1. npm start

See this message in terminal if everything ok.

usaername@0.0.0 start /var/www/html/usaername
node ./bin/www
connection successful

3.Create model and Schema

To create user.js model, first, create a models folder.

mkdir model

Then create new JS file that uses for user.js model.

touch model/user.js

That command create user.js. Now, open and add model fields like Below.

var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var userSchema = new Schema({
fullName: {
type: String,
default: “”,
required: true,
trim: true,
},
email: {
type: String,
default: “”,
required: true,
lowercase: true,
trim: true,
},
phone: {
type: String,
default: “”,
required: true,
trim: true,
},
password: {
type: String,
default: “”,
required: true
}
}, {
timestamps: {
createdAt: ‘created’,
updatedAt: ‘updated’
},
id: false,
toObject: {
virtuals: true,
getters: true,
},
toJSON: {
virtuals: true,
getters: true,
}
});

Now that Schema will mapping to MongoDB collections. Next, export that schema add below
line in model

module.exports = mongoose.model(‘User’, userSchema);
Now, open app.js then add users route as require.

var fs = require(‘fs’);
fs.readdirSync(‘./model’).forEach(function(file) {
var model = file.split(‘.’)[0];
if (model)
require(‘./model/’ + model);
});

4.Create Controller


To make our application more modular and meet MVC pattern, we have to create the controller
for CRUD operations. For that, create new “controllers” folder then create new Javascript file as
the controller.
To create UserController.js controller, first, create a controllers folder.

Mkdir controllers

Then create new Javascript file that uses for user.js model.

touch controllers/UserController.js

That command create UserController.js. Now, open and add require things like database
module, model.

var mongoose = require(“mongoose”);
var User = mongoose.model(“User”);
var userController = {};

Now add these CURD function for users.

userController.create = function (req, res) {
res.render(“../views/users/create”);
};
userController.save = function (req, res) {
var user = new User(req.body);
user.save(function (err) {
if (err) {
console.log(err);
res.render(“../views/users/create”);
} else {
console.log(“Successfully created an User.”);
res.redirect(“/users/show/” + user._id);
}
});
};
userController.edit = function (req, res) {
User.findOne({ _id: req.params.id }).exec(function (err, user) {
if (err) {
console.log(“Error:”, err);
}
else {
res.render(“../views/users/edit”, { user: user });
}
});
};
userController.update = function (req, res) {
User.findByIdAndUpdate(req.params.id, { $set: { fullName: req.body.fullName,
email: req.body.email, phone: req.body.phone } }, { new: true }, function (err,
user) {
if (err) {
console.log(err);
res.render(“../views/users/edit”, { user: req.body });
}
res.redirect(“/users/show/” + user._id);
});
};
userController.list = function (req, res) {

User.find({}).exec(function (err, users) {
if (err) {
console.log(“Error:”, err);
}
else {
res.render(“../views/users/index”, { users: users });
}
});
};
userController.show = function (req, res) {
User.findOne({ _id: req.params.id }).exec(function (err, user) {
if (err) {
console.log(“Error:”, err);
}
else {
res.render(“../views/users/show”, { user: user });
}
});
};
userController.delete = function (req, res) {
User.remove({ _id: req.params.id }, function (err) {
if (err) {
console.log(err);
}
else {
console.log(“User deleted!”);
res.redirect(“/users”);
}
});
};
Now, export user controller as a module write below line in end of the controller file.

module.exports = userController;

5.Create Routes

To redirect the request to the controller before any operations, add routes for user module. Now,
create new js file inside routes folder.

touch routes/users.js

Open users.js and add require things like below and create router.
var express = require(‘express’);
var router = express.Router();
var user = require(“../controllers/UserController.js”);
/* GET users listing. */
router.get(‘/’, user.list);
// Create user
router.get(‘/create’, user.create);
// Save user
router.post(‘/save’, user.save);
// Edit user
router.get(‘/edit/:id’, user.edit);
// Update user
router.post(‘/update/:id’, user.update);
// Show user
router.get(‘/show/:id’, user.show);
// Delete user
router.post(‘/delete/:id’, user.delete);

Now, export router as a module.

module.exports = router;

Now, open app.js then add users route as require.

Var users = require(‘./routes/users);
app.use(‘/users’, usersRouter)

6.Create Views for CRUD

we are creating views for users , add a new folder in views folder like users.

mkdir views/users

Now create new index.ejs inside views/users folder.

touch views/users/index.ejs

Edit index.ejs and add HTML like this.



User List

Create User

User List

<% if(users.length>0) { %> <% for(var i=0; i <% } %>

NamePhone No
User List

Create New User

Name
Email
Phone
Password
  1. edit.ejs



Update User

User List

Create New User

Name
Email
Phone
  1. show.ejs



View User

User List

User Detail

Name:<%= user.fullName%>
Email:<%= user.email%>
Phone No :<%= user.phone%>