Node JS with Express JS and MongoDB REST API

Hey there! If you're diving into web development, you've probably heard about Node.js, Express.js, and MongoDB. But what exactly are they, and how do they come together to create powerful web applications? Well, that's exactly what we will explore in this article.

I'm excited to take you on a journey through the world of building RESTful APIs using Node.js, Express.js, and MongoDB.

So, let's see Node js with express js and MongoDB rest API, build REST API with node, express and MongoDB, and how to create REST API with node js and express, node.js express REST API example.

Step 1: Create an Node.js Application

Create an application using the following command:

npm init -y

Here is the directory structure.

NODE-REST-API
 - controllers
 - db
 - models
 - routes
 - .env
 - app.js
 - productDB.js
 - productDB.json

 

Step 2: Install Dependencies

Now, install dependencies using the following command:

Express.js: A minimalist web application framework for Node.js, simplifying the process of building robust web applications and APIs with ease.

Nodemon: A utility that monitors changes in your Node.js application and automatically restarts the server, enabling a smoother development experience by eliminating the need for manual server restarts after code modifications.

Mongoose: An elegant object modeling tool designed for MongoDB and Node.js, simplifying the interaction with MongoDB databases by providing a schema-based solution and supporting features like validation, querying, and data mapping.

dotenv: A popular Node.js module that loads environment variables from a .env file into process.env, making it easier to manage sensitive or configuration-related information in development environments.

npm i express
npm i nodemon
npm i mongoose
npm i dotenv

 

Step 3: Configure MongoDB

Next, configure MongoDB and establish a connection to the database.

db/conn.js

const mongoose = require("mongoose");

const connectDB = (URI) => {
    return mongoose.connect(URI);
}

module.exports = connectDB;

.env

MONGODB_URI="Add your connection string"

 

Step 4: Create a Model

In this step, we will create the products.js model and define the Product Schema.

models/products.js

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Name must be required"]
    },
    price: {
        type: Number,
        required: [true, "Price must be required"]
    },
    featured: {
        type: Boolean,
        default: false
    },
    rating: {
        type: Number,
        default: 4.5
    },
    createdAt: {
        type: Date,
        default: Date.now()
    },
    company: {
        type: String,
        enum: {
            values: ['Apple', 'Samsung', 'Dell', 'HP'],
        }
    }
});

module.exports = mongoose.model("Product", productSchema);

 

Step 5: Create a Controller

Next, we'll create the products.js controller and define the function to retrieve all products.

controllers/products.js

const Product = require("../models/products");

const getAllProducts = async (req, res) => {

    const products = await Product.find({});
    res.status(200).json({ products })
};

module.exports = getAllProducts;

 

Step 6: Create routes

Next, we'll create routes in the products.js file.

routes/products.js

const express = require('express');
const router = express.Router();
const getAllProducts = require('../controllers/products');

router.route("/").get(getAllProducts);

module.exports = router;

 

Step 7: Create an app.js file

In this step, we will create an app.js file. So, add the following code to that file.

app.js

require("dotenv").config();
const express = require('express');
const app = express();
const connectDB = require("./db/conn");

const PORT = process.env.PORT || 5000;
const product_routes = require("./routes/products");

app.get("/", (req, res) => {
    res.send("Hello");
});

app.use("/api/products", product_routes);

const start = async () => {
    try {
        await connectDB(process.env.MONGODB_URI);
        app.listen(PORT, () => {
            console.log(`${PORT} is connected`);
        });
    } catch (error) {
        console.log(error);
    }
}

start();

 

Step 8: Generate Dummy Records (Optional)

In this step, we will generate dummy records to test the REST API.

products.json

[
    {
        "name":"Iphone 12",
        "price":150,
        "featured":true,
        "company":"Apple"
    },
    {
        "name":"Iphone 13",
        "price":160,
        "featured":true,
        "company":"Apple"
    },
    {
        "name":"Iphone 14",
        "price":170,
        "featured":true,
        "company":"Apple"
    },
    {
        "name":"N4030",
        "price":200,
        "featured":true,
        "company":"Dell"
    },
    {
        "name":"HP 15S",
        "price":250,
        "featured":false,
        "company":"HP"
    },
    {
        "name":"HP Notebook",
        "price":220,
        "featured":true,
        "company":"HP"
    }
]

productDB.js

require("dotenv").config();
const connectDB = require("./db/conn");
const Product = require("./models/products");
const productJson = require("./products.json");
const { Server } = require("http")
const start = async () => {
    try {
        await connectDB(process.env.MONGODB_URI);
        await Product.create(productJson);
        console.log("Success");
    } catch (error) {
        console.log(error);
    }
}

start();

After that, run the following command to create records on the server.

node productDB.js

 

Step 9: Run the Server

Now, execute the following command to start the server.

npm run dev

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS