How to Search Records in REST API using Node JS and MongoDB

Hello there! In this guide, I'll walk you through the process of creating a RESTful API in Node.js and MongoDB that allows you to search records efficiently. We'll be embarking on a step-by-step journey together, starting from setting up our project environment to implementing the search functionality seamlessly.

By the end of this tutorial, you'll have a solid understanding of how to harness the power of Node.js and MongoDB to create a robust API that meets your search needs.

So, let's see how to search records in rest API using node js and MongoDB, how to search records node js express MongoDB, how to search records in MongoDB, and search API in node js MongoDB.

Step 1: Setting Up Your Project

Firstly, let's create a new directory for our project and navigate into it using the terminal or command prompt:

mkdir NODE-REST-API
cd NODE-REST-API

Next, initialize a new Node.js project:

npm init -y

This command will create a package.json file with default settings.

Here, is the directory structure.

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

 

Step 2: Installing Dependencies

We need to install the necessary packages for our project. These include Express.js for building the RESTful API and Mongoose for interacting with MongoDB. Run the following command.

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

 

Step 3: Setting Up Express Server

Now, configure MongoDB and connect 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: Creating a MongoDB Schema:

Now, let's define a schema for our data. In this example, let's assume we are creating a simple 'Products' collection.

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

Now, we will create a 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 { company, name, featured } = req.query;
    const queryObject = {};

    if (company) {
        queryObject.company = company;
    }

    if (name) {
        queryObject.name = {
            $regex: name, $options: "i"
        };
    }

    if(featured){
        queryObject.featured = featured;
    }

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

module.exports = getAllProducts;

 

Step 6: Create a Routes

Now, we will 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 a 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: Run Server

Now, it's time to test our API. Start your server by running:

npm run dev

output:

http://localhost:5000/api/products?name=Notebook

http://localhost:5000/api/products?company=HP

 


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