How to Build Node.js Restful API Project?
Today, I am sharing how to perform CRUD operations using Node Js, Express, Postman, and MongoDB. In my previous articles, I covered the Introduction of Nodejs, Set up the Node Environment, about the MongoDB Atlas. Here I share the Links and read the article.
- Node.js- Introduction, Features, Installation Guide, and Benefits.
- Set Up The Node Environment and Run a Simple Node Server Project.
- How to Create a MongoDB Atlas Account?
Let's start step by step.
1. How to Install the Node-js?
Step 1. Install the node-js. If you have already installed Node-js, skip this step. Here is the link: Download and install Node-js.
Picture 1. When you download the node-js, Check the recommended version and download it.
To verify the installation is correct, Enter the following command.
Node --version or Node -v
JavaScriptCopy
Check the npm version.
npm --version or npm -v
Picture 2. It is showing the installed version.
Step 2. Create a new folder for the project. I created a Node_Restful_API.
Step 3. Open the project folder directory in the vs-code.
Step 4. Open the terminal and open the current folder directory in the terminal.
2. How to Install NPM Package?
Install the npm package; open the terminal and type npm init -y, and enter; it will be installed.
Picture 3. npm init -y
3. Install the npm express, body-parser, nodemon, and mongoose.
Step 5. Express is a node js web application framework. We will install Express.
Here is the link: The Express framework.
npm install express or npm i express
Picture 4. Installed express version 4.18.2.
Step 5. We will install body-parser, nodemon, and Mongoose. Here I link the npm pages to the heading.
- Body-parser. Node.js body parsing middleware.
- Nodemon. Node. Js-based applications by automatically restarting the node application.
- Mongoose. Mongoose is a MongoDB object modeling tool.
I installed three npm packages (body-parser, nodemon, and mongoose).
npm i nodemon body-parser mongoose
Picture 5. You can see the dependencies here. I installed express, body-parser, nodemon, and Mongoose npm packages.
Step 6. Create a serve page serve.js.
const express = require("express");
const app = express();
app.get("/", function (req, res) {
res.send("Hello C# Corner.");
});
app.listen(3000);
const express = require("express"); This line requires express from node_modules.
app.get("/", function (req, res) {
res.send("Hello C# Corner.");
});
It has a callback function (req, res) req = it listens to the incoming request object, and res = responds accordingly using the response object.
Step 7. I execute the start script from package.json.
"scripts": {
"start": "nodemon server.js"
},
Picture 6. Add the Scripts start nodemon server.js
Step 8. Open the terminal and run the node js “npm start”
Picture 7
Step 9. Check the response body in Postman localhost port:3000.
Picture 8. Here you can see this call get method, return “Hello C# Corner.” , Status: success (200 Ok)
4. How to get the MongoDB Connection String?
I installed the Mongoose npm package in our project and Go to the Mongo Atlas page, and got the connection string. I explained in my previous article, How to Create a MongoDB Atlas Account? There is the link. Read this; I continue from this article.
Step 10. Click on Connect button in the cluster in the dashboard.
Picture 9
Picture 10. Click on the Drivers.
Step 11. Open the MongoDB Driver. Select your driver and version, and Add your connection string to your application code.
Picture 11. 01. You will select your driver with the version. 02. You can copy the Connection string.
5. Connect the App with MongoDB
Step 12. Create a mongoose variable const mongoose =require('mongoose');
Connect to the Mongoose.
mongoose.
connect("mongodb+srv://<Username>:<Password>@mongodbcluster01.joofg8v.mongodb.net/<your_database_name>?retryWrites=true&w=majority")
.then(() => {
console.log("connected to MongoDB");
app.listen(3000, () => {
console.log(`Node API app is running on port 3000`);
});
})
.catch((error) => {
console.log(error);
});
For the DB connection string, you will add your database name, and the connection will succeed app listens to port:3000.
Picture 12. you can see the connected db and success message “connected to MongoDB”.
6. Create a Model for Data in the Database.
Picture 13 I’m going to explain this diagram: Node apps have Models. On-site, the model has a schema; I’m Going to create a productModel.js file, With productSchema. Let’s we to the steps by step.
Step 13. Create a new folder as models.
Step 14. Create a productModel.js page. And Continue this code.
const mongoose = require("mongoose");
const productSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, "Please enter a product name"],
},
quantity: {
type: Number,
required: true,
default: 0,
},
price: {
type: Number,
required: true,
},
image: {
type: String,
required: false,
},
},
{
timestamps: true,
}
);
const Product = mongoose.model("Product", productSchema);
module.exports = Product;
Include the mongoose in our code and is a require =const mongoose = require("mongoose");
Mongoose has a Schema. We can create a Schema from Mongoose productSchema is init const productSchema = mongoose.Schema()
Schema is the object. Inside the object, we create the field. In the field, the object has a data type.
const Product = mongoose.model("Product", productSchema);
module.exports = Product;
const Product = mongoose.model("Product", productSchema); This line creates a model. I’m going to create a model product from Mongoose, the first parameter model name, and the second parameter Schema name. The model will export.
module.exports = Product;
7. Use a Model to Save Data in MongoDB.
const express = require("express");
const mongoose = require("mongoose");
const Product = require("./models/productModel");
const app = express();
app.use(express.json());
app.post("/product", async (req, res) => {
try {
const product = await Product.create(req.body);
res.status(200).json(product);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
Here we Import the product model const Product = require("./models/productModel");
Here add the express json middleware; the application understands json. app.use(express.json()); an application can accept json data type.
app.post("/product", async (req, res) => {
})
App. post from express, Call the route as a “ /product “.
const product = await Product.create(req.body);
res.status(200).json(product);
model. create(req.body) Product is Model, return status (200) success and product.
Now we can check the route in Postman.
Step 15. Go to the Postman and set the address http://localhost:3000/productset method in POST and Click on the Send button.
Picture 14. Successfully save the data in the database. Get status 200.
We can check whether the data was added or not in MongoDB.
Picture 15. Node_RestfulAPI is a Database. “Products” is a collection. Now we can see the documents here.
8. Fetch or Get Data from the Database.
app.get("/products", async (req, res) => {
try {
const products = await Product.find({});
res.status(200).json(products);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
Get the data(Documents) from dbconst products = await Product.find({}); This line get the data from the model.
Picture 16. Fetch or Get Data; you can see the product list here.
A. Get a single data from the database.
app.get("/products/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findById(id);
res.status(200).json(product);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
Get the product by the id of the product from the products collection.
app.get("/products/:id", async (req, res) => {
});
It’s a get method called “products/:id”. This line calls the id. It's the id of the products.
const { id } = req.params;
Get the id from url, deconstruct {id} from request params.
const product = await Product.findById(id);
Get the single product from find by id (deconstruct -id).
Let's check the Postman's result.
Picture 17: Get Data by product id. It’s a single data from the Database(products).
9. Update or Edit Data in the Database
app.put("/products/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findByIdAndUpdate(id, req.body);
// we cannot find any product in database
if (!product) {
return res
.status(404)
.json({ message: `cannot find any product with ID ${id}` });
}
const updatedProduct = await Product.findById(id);
res.status(200).json(updatedProduct);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
Deconstruct the id, Product model use the find by id and update we pass the two parameters (id, request body).
const product = await Product.findByIdAndUpdate(id, req.body);
The product is found by id and updates the data from the request body(Edit data).
if (!product) {
return res
.status(404)
.json({ message: `cannot find any product with ID ${id}` });
}
Check the product after the update. Product is not there, return the error message with the status (404).
We will check the Postman. With the id: "_id": "64b7feef3001fa966450c413",
{
"_id": "64b7feef3001fa966450c413",
"name": "Face powder",
"quantity": 50,
"price": 1500,
"image": "https://static.javatpoint.com/list/images/list-of-cosmetic-products5.jpg",
"createdAt": "2023-07-19T15:19:11.607Z",
"updatedAt": "2023-07-19T15:19:11.607Z",
"__v": 0
},
Picture 18. Get Data by product id and Update the data. Now we can see the updated data here.
Picture 19. We can see the updated data here by "_id": "64b7feef3001fa966450c413",
10. Delete or Remove Data from the Database
// Delete a product
app.delete("/products/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findByIdAndDelete(id);
if (!product) {
return res
.status(404)
.json({ message: `cannot find any product with ID ${id}` });
}
res.status(200).json(product);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
Get the id and delete it from the product Product.findByIdAndDelete(id);
Product finds by Id and removes the data from the database. We are removing "_id": "64b7ff633001fa966450c417", This id
{
"_id": "64b7ff633001fa966450c417",
"name": "Mascara",
"quantity": 50,
"price": 1000,
"image": "https://static.javatpoint.com/list/images/list-of-cosmetic-products10.jpg",
"createdAt": "2023-07-19T15:21:07.454Z",
"updatedAt": "2023-07-19T15:21:07.454Z",
"__v": 0
}
Picture 20. Successfully removed Product by "_id": "64b7ff633001fa966450c417",
Summary
In my article, I explained how to perform CRUD operations using Node Js, Express, Postman, and MongoDB. In this article, I covered How to install the NODE, NPM, Express, Body-parser, Nodemon, and Mongoose. And also Connect the MongoDB with APP. Perform CRUD operations API checking with Postman. I hope this article helps those Who have an interest in self-learning. To Keep in touch with me, Next article i’m going to cover Understanding MVC pattern in Node Js