Skip to main content
nodejs-mongodb-express-mongoose

CRUD Operations using NodeJS, Express, MongoDB and Mongoose

This is another nodejs and express.js tutorial which helps to create CRUD operations using Mongodb and Mongoose ORM. Mongodb is a popular open-source no-SQL database. The Mongoose is ORM(Object-relational mapping) that provides helpful methods to do operations with Mongodb collections.

I have already shared Add, Edit and Delete Record Using MySQL and Node js Rest Api to Add, Edit and Delete Record from MySQL Using Express JS.I am assuming you have installed mongodb into your server.

nodejs-mongodb-express-mongoose

This nodejs tutorial is the extended tutorial of nodejs and express.js rest API tuts. I will use mongodb as a database and mongoose ORM to do operations on mongo models. I will create an HTTP rest call to fetch mongodb collections details, create a record into mongodb, update the record into mongodb and delete collections.

We will cover the following functionality in this node js tutorial:

  • How to create a database connection with Mongodb.
  • How to create a Model using Mongoose.
  • How to create a collection in Mongodb using Mongoose.
  • How to delete collection in Mongodb using Mongoose.
  • How to update Collection in Mongodb using Mongoose.
  • Creating CRUD operation REST API using Node, ExpressJS, MongoDB and Mongoose.

The Node js Rest API details are as follows:

RouteMethodTypePosted JSONDescription
/employeesGETJSONGet all employees data
/employees/{id}GETJSONGet a single employee data
/employeesPOSTJSON{"employee_name": "Adam", "employee_age": "34", "employee_salary" : "23421"}Insert new employee records into the database
/employeesPUTJSON{"employee_name": "Adam", "employee_age": "34", "employee_salary" : "23421", "id":21}Update employee records into the database
/employeesDELETEJSON{"id" : 59}Delete particular employee record from a database

I am using the following files and folder

I am creating a folder 'nodejs-restapi-mongoose-example'.This is our nodejs project name.

package.json: This file will have all nodejs dependencies module for this example.
config/database.js: This file will be used for database connection parameters for Mongodb.
model/employee.js: This file will be used to create employee schema and model.
main.js: This file will use to create nodejs application server and routes url.
node_modules folder: This folder will contain all nodejs packages.

How to install package dependencies into Nodejs app

We will create package.json file into 'nodejs-restapi-mongoose-example' folder and add the below modules in this file.

{
  "name": "nodejs-mongoose-example",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": {
    "name": "Adam",
    "email": "[email protected]",
    "url": "http://js-tutorials.com/"
  },
  "license": "MIT",
  "dependencies": {
    "express": "~4.13.2",
    "mongoose": "~3.6.2",
    "body-parser": "~1.14.1",
    "method-override": "~2.3.5"
  }
}

We will open a command line and cd to ‘nodejs-restapi-mongoose-example’ folder and run the below command to install dependencies modules into 'node_modules' folder.

d:\nodejs-restapi-mongoose-example > npm install

Step 1: We will create database.js connection file into the config folder, The connection URL of mongodb will add here like below,

// config/database.js
module.exports = {
    url : 'mongodb://localhost/'
};

Step 2: We will create employee.js model file into a model folder, We will create schema and register the Employee model.

// load mongoose since we need it to define a model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
EmpSchema = new Schema({
    name : String,
    salary : Number,
	age : Number
});
module.exports = mongoose.model('Employee', EmpSchema);

The line #2 , used to get mongoose ORM instance.

Step 3: We will create and add dependency modules into the main nodejs file, created main.js file and included all required modules like below,

var express  = require('express');
var mongoose = require('mongoose');
var app      = express();
var database = require('./config/database');
var bodyParser = require('body-parser');         // pull information from HTML POST (express4)
var methodOverride = require('method-override');

var port     = process.env.PORT || 8888;
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());

var Employee = require('./models/employee');

mongoose.connect(database.url);

app.listen(port);
console.log("App listening on port : " + port);

Also Checkout other tutorials of nodejs rest api,

Node.js Rest API to fetch all records from MongoDB Using Mongoose

We will create a GET Rest Request to access all employee records from MongoDB. We will use mongodb query to fetch data from the employee table and send JSON data to the client as a response object.

//get all employee data from db
app.get('/api/employees', function(req, res) {
	// use mongoose to get all todos in the database
	Employee.find(function(err, employees) {
		// if there is an error retrieving, send the error otherwise send data
		if (err)
			res.send(err)
		res.json(employees); // return all employees in JSON format
	});
});

The Employee.find use to get all records from the database. The res.end() method sends data to the client in a JSON string through JSON.stringify() method.

Now access http://localhost:8888/employee rest api URL from the browser and you will get an all employees record from Mongo database.

Rest Api to get a single record from Mongodb Using Node.js and ExpressJS

We will create a GET type rest request to access a single employee record from mongodb. We will use find() method of mongoose and pass desired employee id. We will send JSON data to the client as a response object.

// get a employee with ID of 1
app.get('/api/employees/:employee_id', function(req, res) {
	let id = req.params.employee_id;
	Employee.findById(id, function(err, employee) {
		if (err)
			res.send(err)

		res.json(employee);
	});

});

Rest Api to Create New Record into Mongodb Using Node.js and ExpressJS

We will create a new Rest API to create a new employee data entry into Mongodb table using node.js. I will create a POST type Rest request because We will post some JSON data to the node server.

// create employee and send back all employees after creation
app.post('/api/employees', function(req, res) {
	// create mongose method to create a new record into collection
	Employee.create({
		name : req.body.name,
		salary : req.body.salary,
		age : req.body.age
	}, function(err, employee) {
		if (err)
			res.send(err);

		// get and return all the employees after newly created employe record
		Employee.find(function(err, employees) {
			if (err)
				res.send(err)
			res.json(employees);
		});
	});

});

Employee.create method used to create new documents for employee collection.

Rest Api to Update Record into Mongodb Using Node JS

We will create a new PUT type Restful API request using nodejs and express to update data into mongodb database.We need to pass the employee id which will use to update the record into the table.

// create employee and send back all employees after creation
app.put('/api/employees/:employee_id', function(req, res) {
	// create mongose method to update a existing record into collection
	let id = req.params.employee_id;
	var data = {
		name : req.body.name,
		salary : req.body.salary,
		age : req.body.age
	}

	// save the user
	Employee.findByIdAndUpdate(id, data, function(err, employee) {
	if (err) throw err;

	res.send('Successfully! Employee updated - '+employee.name);
	});
});

We have created JSON data and sent mongoose ORM using Employee.findByIdAndUpdate(), this method takes the first parameter employee_id which we want to update and the second is updated data in JSON format.

Delete Record from Mongodb collection

We will create a new DELETE Type rest API request using node js to remove employee records from Mongodb collection. We will pass employee id as a parameter that you want to delete from Mongodb collection.

// delete a employee by id
app.delete('/api/employees/:employee_id', function(req, res) {
	console.log(req.params.employee_id);
	let id = req.params.employee_id;
	Employee.remove({
		_id : id
	}, function(err) {
		if (err)
			res.send(err);
		else
			res.send('Successfully! Employee has been Deleted.');	
	});
});

Conclusion

We have created a simple Nodejs application to do crud operations using express.js and Mongodb.We have also connected Mongodb and used Mongoose ORM. Create Rest API to get all employees, get a single employee record, create new employee entry, update employee data and delete employee data from MongoDB Collection through mongoose framework.

You can download the source code from the link below.

2 thoughts to “CRUD Operations using NodeJS, Express, MongoDB and Mongoose”

  1. Hello,

    Can you please give example how to insert child record for parent. for ex. Account as a parent and Activities as child

Leave a Reply

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