Hey there! Welcome to my article on creating a RESTful API using Node.js and MongoDB. If you're looking to build powerful and scalable web applications, understanding how to create a robust API is essential.
In this guide, I'll walk you through the process of building a REST API step by step using express.js and mongoDB.
A REST API utilizes various HTTP methods to perform operations on resources. It typically employs a GET request to retrieve a record, a POST request to create one, a PUT request to update a record, and a DELETE request to delete one.
These HTTP methods provide a standardized way for clients to interact with the server and perform CRUD (Create, Read, Update, Delete) operations on resources.
So, let's see how to create a REST API using node js and MongoDB, express.js, and MongoDB rest API, how to create a rest API with node js and express, and how to create REST API in node.js.
Ensure Node.js is installed on your machine. You can download it from the official Node.js website and follow the installation instructions.
Install MongoDB Community Edition from the official MongoDB website and set it up on your local machine or use a cloud-based MongoDB service like MongoDB Atlas.
Create a new directory for your project. Initialize a new Node.js project using npm (Node Package Manager):
mkdir my-app
cd my-app
npm init -y
Install necessary dependencies such as Express.js (for building the API) and Mongoose (for interacting with MongoDB):
npm install -g express-generator
npx express --view=ejs
npm install
npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install cors --save
npm install mongoose
body-parser: Parse incoming request bodies in a middleware before your handlers, available under the req.body
property.
Express-Flash: Flash is an extension of connect-flash
with the ability to define a flash message and render it without redirecting the request.
Express-Session: HTTP server-side framework used to create and manage a session middleware.
Express-EJS: EJS is a simple templating language that is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages
Mongoose: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.
Set up a connection to your MongoDB database using Mongoose:
database.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/my_database', {useNewUrlParser: true});
var conn = mongoose.connection;
conn.on('connected', function() {
console.log('database is connected successfully');
});
conn.on('disconnected',function(){
console.log('database is disconnected successfully');
});
conn.on('error', console.error.bind(console, 'connection error:'));
module.exports = conn;
Define a schema for your MongoDB documents and create a model using Mongoose. This will define the structure of your data.
userModel.js
var db = require("../database");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
title: String,
author: String,
category: String
});
module.exports = mongoose.model('User', UserSchema);
Implement controller functions for handling CRUD operations on your MongoDB data.
users.js route file
var express = require('express');
var User = require('../models/user');
var router = express.Router();
router.get('/', function(req, res){
console.log('getting all users');
User.find({}).exec(function(err, users){
if(err) {
res.send('error has occured');
} else {
console.log(users);
res.json(users);
}
});
});
router.get('/:id', function(req, res){
console.log('getting one user');
User.findOne({
_id: req.params.id
}).exec(function(err, user){
if(err) {
res.send('error has occured');
} else {
console.log(user);
res.json(user);
}
});
});
router.post('/', function(req, res){
var newUser = new User();
newUser.title = req.body.title;
newUser.author = req.body.author;
newUser.category = req.body.category;
newUser.save(function(err, user){
if(err) {
res.send('error saving user');
} else {
console.log(user);
res.send(user);
}
});
});
router.put('/:id', function(req, res){
User.findOneAndUpdate({
_id: req.params.id
},{
$set: {
title: req.body.title,
author: req.body.author,
category: req.body.category
}
},{
upsert: true
},function(err, newUser){
if(err) {
res.send('error updating user');
} else {
console.log(newUser);
res.send(newUser);
}
});
});
router.delete('/:id', function(req, res){
User.findByIdAndRemove({
_id: req.params.id
},function(err, user){
if(err) {
res.send('error deleting user');
} else {
console.log(user);
res.send(user);
}
});
});
module.exports = router;
Import express flash session body-parser Mongoose dependencies in app.js as shown below.
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const users = require('./routes/users');
const app = express();
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(cors());
app.use('/users', users);
// Handling Errors
app.use((err, req, res, next) => {
// console.log(err);
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
message: err.message,
});
});
app.listen(3000,() => console.log('Server is running on port 3000'));
Start the app server using the following command.
npm start
You might also like: