Node JS Express MongoDB CRUD Example (2024)
In this article, we'll demonstrate how to create a Node.js Express MongoDB CRUD example by using routes and create below RESTful API endpoints for POST, GET, PUT, DELETE.
Node JS Express MongoDB POST, GET, PUT, DELETE Rest Api's
POST
- Create Employee RecordGET
- List all employeesGET
- Get employees by it's idPUT
- Update/Edit selected employee detailsDELETE
- Remove selected employee recordDELETE
- RemoveAll employees.
Refer node js installation steps from Node.js Installation and NPM Tutorial
What is Mongoose used for?
Mongoose is a MongoDB and Node.js based Object Data Modeling (ODM) library. It keeps track of data relationships, does schema validation, and converts code objects into MongoDB representations.
Express apps can use any database that Node supports. There are several popular choices, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.
Refer to Installing MongoDB on Windows and Starting Up.
Create Express Crud Project
Create Express application skeleton instantly by using the express-generator
application generator tool using below commands:
npm install -g express-generator
express
Now install dependencies.
npm install
Install Mongoose dependency
Mongoose is a MongoDB dependency that maps a document into a JS Object containing all of its data.
npm i mongoose
Project Structure
According to the project's use case or requirements, we can create files and folders.
Checkout our related posts :
Add MongoDB connection details
Create the new folder config
and new file
database-config.js
.
const mongoose = require('mongoose');
mongoose.set("strictQuery", false);
const db_url = 'mongodb://127.0.0.1:27017/TechGeekNextDB';
const connection = () => {
mongoose.connect(db_url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(()=>console.log('Database connected!'))
.catch(e=>console.log(e));
};
module.exports = connection;
Test MongoDB Connection
Start the express mongodb application by using the npm start
command after providing
the MongoDB
connection
information. If everything goes smoothly, carry on with the rest endpoints;
Express Crud Dependencies
In Express, all of the necessary dependencies are listed in the package.json
file.
It
contains scripts to start, build, test and eject the Express JS application.
{
"name": "express-crud-mongo",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "^1.18.3",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongoose": "^6.9.0",
"morgan": "~1.9.1"
}
}
Change Default Node js Port as per requirement
From the generated bin/www
file, change the default port from 3000
to
8080
.
Express MongoDB CRUD App - App component
- The App component (
App.js
) is the application's root container. - Default Code base with error handling will be generated by the express application generator tool.
- Change the code for
usersRouter
as given below:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const connection = require('./config/database-config');
const cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/employee');
var app = express();
app.disable('etag');
app.use(cors({
origin: '*'
}));
connection();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Express MongoDB CRUD Example - Create Model
Create a Model to outline the structure of our employee database. Create the folder
model
and inside create the file employee.js
to define the structure of
employee document to map with database.
const mongoose = require('mongoose');
const EmployeeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
role: {
type: String,
required: true
}
});
module.exports = mongoose.model('employee', EmployeeSchema);
Express MongoDB CRUD Example - Create Route rest endpoints
- Create the page
employee.js
underroutes
folder. - Create CRUD rest endpoints.
var express = require('express');
const connection = require('../config/database-config');
const employee = require('../models/employee');
var router = express.Router();
/* Add new employee*/
router.post('/employee', async (req, resp, next) => {
const { name, role } = req.body;
try {
const newEmployee = new employee({
name: name,
role: role
});
const savedEmployee = await newEmployee.save();
resp.json(savedEmployee);
} catch (error) {
next(error);
}
});
/* GET all employees listing. */
router.get('/employees', async (req, resp, next) => {
try {
const employees = await employee.find();
var records = [];
employees.forEach(emp => {
if (emp) {
const empsRecord =
{
id: emp._id,
name: emp.name,
role: emp.role
}
records.push(empsRecord);
}
});
resp.json(records);
} catch (error) {
next(error);
}
});
/* Get employee based on id*/
router.get('/employee/:id', async (req, resp, next) => {
try {
const emp = await employee.findById(req.params.id);
resp.json(
{
id: emp._id,
name: emp.name,
role: emp.role
}
);
} catch (error) {
next(error);
}
});
/* Edit existing employee based on id*/
router.put('/employee/:id', async (req, resp, next) => {
try {
const requestBody = { name: req.body.name, role: req.body.role };
let emp_rec = await employee.findById(req.params.id);
if (!emp_rec)
return res.status(404).json({ msg: 'Employee record not found' });
const updatedEmp = await employee.findByIdAndUpdate(
req.params.id, requestBody, { new: true });
resp.json(updatedEmp);
} catch (error) {
next(error);
}
});
/* Delete employee based on id*/
router.delete('/employee/:id', async (req, resp, next) => {
try {
const emp = await employee.findByIdAndDelete(req.params.id);
resp.send(`Employee ${emp.name} record deleted!`)
} catch (error) {
next(error);
}
});
/* Delete all employees*/
router.delete('/employees', async (req, resp, next) => {
try {
const emp = await employee.remove({});
resp.send(`All employee records has been deleted!`)
} catch (error) {
next(error);
}
});
module.exports = router;
Test Express MongoDB CRUD Example
- Use below command to install all the dependencies required for the project.
npm install
- Run the application by using below command:
npm start
- The application will open in browser at our configured port http://localhost:8080/ url.
Create New Employee
Open Postman, use POST method with end point http://localhost:8080/employee and provide Employee details to create new employee record.List Employees
Use GET method with end point http://localhost:8080/employees to get all employees.Get Employee
Use GET method with end point http://localhost:8080/employee/63da4c23ce6d10849022098c to get employee by id, where63da4c23ce6d10849022098c
is generated employee id by MongoDB.Edit Employee
Use PUT method with end point http://localhost:8080/employee/63da4c57ce6d10849022098e where63da4c57ce6d10849022098e
is the id of the employee and provide employee details as body in Postman to edit.Delete Employee
Use DELETE method with end point http://localhost:8080/employee/63da4c57ce6d10849022098e where63da4c57ce6d10849022098e
is the id of the employee.Delete All Employees
Use DELETE method with end point http://localhost:8080/employees to delete all employees records from database.
Refer React Crud Example for front end crud implementation.
Download Source Code
The full source code for this article can be found on below.Download it here - Express MongoDB Crud Example
Refer Node JS Express MYSQL Crud Example.