DEV Community

Cover image for RESTful API CRUD Node, Express, MongoDB Atlas, Mongoose, #Hosting on Render #POSTMAN
swapnanilWebDeveloper
swapnanilWebDeveloper

Posted on

RESTful API CRUD Node, Express, MongoDB Atlas, Mongoose, #Hosting on Render #POSTMAN

1) Hello guys I have created Another API by Node.js, Express.js, MongoDB Atlas, Mongoose and then finally hosted on both localhost-web-browser and Render.

Special notes : ==>

To get THE full code follow my github repository link given below => click here to get full code

Hosted this API on render and links are =>
a) get all students
b) get all students by name
c)get all students by gender and hobby
d)get all students by age and hobby
e)get all students by address
f)get students by marks in physics,chemistry,mathematics
g)get all students by total and grade

2) I have used postman to execute POST , GET, PATCH, DELETE requests.

3) Now I will be starting with folder and file structure.
4) Create a folder called MyStudentAPI and create folder src inside MyStudentAPI then create folders like => controllers , db , connect , routes , calculateGradeTotal inside src folder.

5) Then install some packages like =>
npm install express
npm install mongoose
npm install mongodb
npm install dotenv

6) Then create app.js file inside src folder

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

const PORT = process.env.PORT || 7070 ;

const students_routes  = require("./routes/students");

app.use(express.json());

app.get("/", (req, res) => {
    res.send("Hello I am going to create a API on student data...!!!");
});

// middleware or to set router
app.use("/api/students", students_routes);

const startStudentInformation = async (req,res) => {
    try{
      const res = await connectDB(process.env.MONGODB_URL);
      if(res){
        console.log("Connection successfull !! ");
      }
      else{
        console.log("Something wrong with Connection to Database...");
      }
       app.listen(PORT, () => {
         console.log(`${PORT} Yes I am connected !!`);
       });
    }
    catch(err){
      console.log("Something went wrong !!! : "+err);
    }
 }

 startStudentInformation();

Enter fullscreen mode Exit fullscreen mode

7) Then create students.js inside routes folder

const express = require("express");
const router = express.Router();

const {
    getAllStudents, // pagination , limit
    getAllStudentsByName, // sort, select, name.first, name.last, regEx...
    getAllStudentsByHobbiesGender, // sort, select, hobby, gender 
    getAllStudentsByAgeRangeAndHobbies, // sort, select, age range
    getAllStudentsByAddress, // sort, select , address state/district/city , regEx..
    getAllStudentsByScienceMarksRange, // sort, select, science physics/chemistry/mathematacis ..... 
    getAllStudentsByTotalGrade, // sort, select, total range , grade...

} = require("../controllers/studentsA");

const {
    createNewStudent,
    updateStudentByName,
    updateStudentByAddress,
    deleteStudentByName,
    deleteStudentByAddress,

} = require("../controllers/studentsB");

router.route("/").get(getAllStudents);
router.route("/Name").get(getAllStudentsByName);
router.route("/HobbyGender").get(getAllStudentsByHobbiesGender);
router.route("/AgeHobby").get(getAllStudentsByAgeRangeAndHobbies);
router.route("/Address").get(getAllStudentsByAddress);
router.route("/Marks").get(getAllStudentsByScienceMarksRange);
router.route("/TotalGrade").get(getAllStudentsByTotalGrade);

router.route("/createStudent").post(createNewStudent);
router.route("/updateStudentbyName").patch(updateStudentByName);
router.route("/updateStudentbyAddress").patch(updateStudentByAddress);
router.route("/deletebyName").delete(deleteStudentByName);
router.route("/deletebyAddress").delete(deleteStudentByAddress);

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

8) Now come to models folder and create students.js file inside it then write code inside it like given below =>


const mongoose = require("mongoose");

const studentSchema = new  mongoose.Schema({
    name : {
        first : {
            type : String,
            required : true,
        },
        last : {
            type : String,
            required : true,
        }
    },
    age : {
        type : Number,
        required : [true, "Please fill the age field ...!!!"]
    },
    isAlive : {
        type : Boolean,
        default : true,
    },
    gender : {
        type : String,
        default : "Male",
        enum : {
            values : ["Male", "Female", "Others"],
            message : `${this.values} is not supported`,
        }
    },
    address : {
        state : { type : String, required : [true, "Please Provide state ...."]},
        district : { type : String, required : [true, "Please Provide district ...."]},
        city : { type : String, required : [true, "Please Provide city ...."]},
    },
    science : {
        physics : { type : Number, require : [true, "Please provide marks of physics..."]},
        chemistry : { type : Number, require : [true, "Please provide marks of chemistry..."]},
        mathematics : { type : Number, require : [true, "Please provide marks of mathematics..."]}
    },
    total : {
      type : Number,
      default : 90,
    },
    average : {
        type : Number,
        required : [true, "Average is not calculated..!!!"]
    },
    grade : { 
        type : String,
        default : "Good",
    },
    hobbies : [String],
});

const Student = mongoose.model('Student', studentSchema);

module.exports = Student;

Enter fullscreen mode Exit fullscreen mode

9) Then go to Controllers folder and craete studentA.js and studentsB.js file inside it and

write code inside studentsA.js =>


const Student = require("../models/students");

const getAllStudents= async (req,res) => {
    try{
        const {sort, select} = req.query;

        let studentData = Student.find(); 

        if(sort){
            let sortFIx = sort.replaceAll(",", " ");
            console.log(sortFIx);
            studentData = studentData.sort(sortFIx);
        }

        if(select){
            let selectFIx = select.replaceAll(",", " ");
            console.log(selectFIx);
            studentData = studentData.select(selectFIx);
        }

        let page = Number(req.query.page) || 1;
        let limit = Number(req.query.limit) || 5;

        let skip = (page - 1) * limit ;

        studentData = studentData.skip(skip).limit(limit);

        const resStudent = await studentData;
        console.log(resStudent);
        console.log(req.query);
        res.status(200).json({resStudent, lengthOfStudentList : resStudent.length});
    }
    catch(error){
        res.status(400).json("something went wrong while getting all the students : "+error);
    } 
}

const getAllStudentsByName = async (req,res) => {
        try{
            const {firstName, lastName, select, sort} = req.query;
            let queryObject = {};

            let studentData = Student.find();

            if(firstName){
                queryObject.firstName = { $regex : firstName , $options : 'i'},
                console.log(queryObject);
                console.log(queryObject.firstName);
                studentData = studentData.find({"name.first" : queryObject.firstName });
            }

            if(lastName){
                queryObject.lastName = { $regex : lastName , $options : 'i'} 
                console.log(queryObject);
                console.log(queryObject.lastName);
                studentData = studentData.find({"name.last" : queryObject.lastName});
            }

            if(select){
                let selectFIx = select.replaceAll(",", " ");
                console.log(selectFIx);
                studentData = studentData.select(selectFIx);
            }

            if(sort){
                let sortFIx = sort.replaceAll(",", " ");
                console.log(sortFIx);
                studentData = studentData.sort(sortFIx);
            }

            const resStudent = await studentData;
            console.log(resStudent);
            console.log(req.query);
            res.status(200).json({resStudent, lengthOfStudentList : resStudent.length})
        }
        catch(error){
            res.status(400).send("Something went wrong while getting all students by name : "+error);
        }
}

const getAllStudentsByHobbiesGender = async (req,res) => {
    try{
        const {hobbies , gender, sort, select} = req.query;
        const queryObject = {};

        let studentData = Student.find(); 

        if(sort){
            let sortFIx = sort.replaceAll(",", " ");
            console.log(sortFIx);
            studentData = studentData.sort(sortFIx);
        }

        if(select){
            let selectFIx = select.replaceAll(",", " ");
            console.log(selectFIx);
            studentData = studentData.select(selectFIx);
        }

        if(gender){
            queryObject.gender = gender;
            console.log(queryObject);
            console.log(queryObject.gender);
            studentData = studentData.find(queryObject)
        }

        if(hobbies){
            queryObject.hobbies = hobbies.split(",");
            console.log(queryObject);
            console.log(queryObject.hobbies);
            studentData = studentData.find({hobbies : { $all : queryObject.hobbies } })
        }

        const resStudent = await studentData;
        console.log(resStudent);
        console.log(req.query);
        res.status(200).json({resStudent, lengthOfStudentList : resStudent.length});
    }
    catch(error){
        res.status(400).json("something went wrong while getting all the students by Gender and hobbies: "+error);
    }
}

const getAllStudentsByAgeRangeAndHobbies= async (req,res) => {
    try{
        const {ageMax, ageMin, hobbies, sort, select} = req.query;
        const queryObject = {};

        let studentData = Student.find(); 

        if(sort){
            let sortFIx = sort.replaceAll(",", " ");
            console.log(sortFIx);
            studentData = studentData.sort(sortFIx);
        }

        if(select){
            let selectFIx = select.replaceAll(",", " ");
            console.log(selectFIx);
            studentData = studentData.select(selectFIx);
        }

        if(ageMax){
            queryObject.ageMax = ageMax;
            console.log(queryObject);
            console.log(queryObject.ageMax);
            studentData = studentData.find({ age : {$lte : queryObject.ageMax}});
        }

        if(ageMin){
            queryObject.ageMin = ageMin;
            console.log(queryObject);
            console.log(queryObject.ageMin);
            studentData = studentData.find({ age : { $gte : queryObject.ageMin}});
        }

        if(hobbies){
            queryObject.hobbies = hobbies.split(",");
            console.log(queryObject);
            console.log(queryObject.hobbies);
            studentData = studentData.find({hobbies : { $all : queryObject.hobbies } })
        }

        const resStudent = await studentData;
        console.log(resStudent);
        console.log(req.query);
        res.status(200).json({resStudent, lengthOfStudentList : resStudent.length});
    }
    catch(error){
        res.status(400).json("something went wrong while getting all the students by age range and hobbies: "+error);
    }
}

const getAllStudentsByAddress= async (req,res) => {
    try{
        const {state, district , city, sort, select} = req.query;
        const queryObject = {};

        let studentData = Student.find();

        if(sort){
            let sortFIx = sort.replaceAll(",", " ");
            console.log(sortFIx);
            studentData = studentData.sort(sortFIx);
        }

        if(select){
            let selectFIx = select.replaceAll(",", " ");
            console.log(selectFIx);
            studentData = studentData.select(selectFIx);
        }

        if(state){
            queryObject.state ={ $regex : state , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.state);
            studentData = studentData.find({"address.state" : queryObject.state})
        }

        if(district){
            queryObject.district = { $regex : district , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.district);
            studentData = studentData.find({"address.district" : queryObject.district});
        }

        if(city){
            queryObject.city = { $regex : city, $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.city);
            studentData = studentData.find({"address.city" : queryObject.city});
        }

        const resStudent = await studentData;
        console.log(resStudent);
        console.log(req.query);
        res.status(200).send({resStudent, lengthOfStudentList : resStudent.length});
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all students by address : "+error);
    }
}

const getAllStudentsByScienceMarksRange = async (req,res) => {
    try{
        const {phyMin, phyMax, chemMin, chemMax, mathMin, mathMax, sort, select} = req.query;
        const queryObject = {};

        let studentData = Student.find();

        if(sort){
            let sortFIx = sort.replaceAll(",", " ");
            console.log(sortFIx);
            studentData = studentData.sort(sortFIx);
        }

        if(select){
            let selectFIx = select.replaceAll(",", " ");
            console.log(selectFIx);
            studentData = studentData.select(selectFIx);
        }

        if(phyMin){
            queryObject.phyMin = phyMin;
            console.log(queryObject);
            console.log(queryObject.phyMin);
            studentData = studentData.find({"science.physics" : {$gte : phyMin} })
        }

        if(phyMax){
            queryObject.phyMax = phyMax;
            console.log(queryObject);
            console.log(queryObject.phyMax);
            studentData = studentData.find({"science.physics" : {$lte : phyMax} })
        }

        if(chemMin){
            queryObject.chemMin = chemMin;
            console.log(queryObject);
            console.log(queryObject.chemMin);
            studentData = studentData.find({"science.chemistry" : {$gte : chemMin} })
        }

        if(chemMax){
            queryObject.chemMax = chemMax;
            console.log(queryObject);
            console.log(queryObject.chemMax);
            studentData = studentData.find({"science.chemistry" : {$lte : chemMax} })
        }

        if(mathMin){
            queryObject.mathMin = mathMin;
            console.log(queryObject);
            console.log(queryObject.mathMin);
            studentData = studentData.find({"science.mathematics" : {$gte : mathMin} })
        }

        if(mathMax){
            queryObject.mathMax = mathMax;
            console.log(queryObject);
            console.log(queryObject.mathMax);
            studentData = studentData.find({"science.mathematics" : {$lte : mathMax} })
        }

        const resStudent = await studentData;
        console.log(resStudent);
        console.log(req.query);
        res.status(200).send({resStudent, lengthOfStudentList : resStudent.length});
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all science marks range  : "+error);
    }
}

const getAllStudentsByTotalGrade = async (req,res) => {
    try{
        const {totalMin, totalMax, grade, sort, select} = req.query;
        const queryObject = {};

        let studentData = Student.find(); 

        if(sort){
            let sortFIx = sort.replaceAll(",", " ");
            console.log(sortFIx);
            studentData = studentData.sort(sortFIx);
        }

        if(select){
            let selectFIx = select.replaceAll(",", " ");
            console.log(selectFIx);
            studentData = studentData.select(selectFIx);
        }

        if(totalMax){
            queryObject.totalMax = totalMax;
            console.log(queryObject);
            console.log(queryObject.totalMax);
            studentData = studentData.find({ total : {$lte : queryObject.totalMax}});
        }

        if(totalMin){
            queryObject.totalMin = totalMin;
            console.log(queryObject);
            console.log(queryObject.totalMin);
            studentData = studentData.find({ total : { $gte : queryObject.totalMin}});
        }

        if(grade){
            queryObject.grade = { $regex : grade , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.grade);
            studentData = studentData.find({grade : queryObject.grade});
        }

        const resStudent = await studentData;
        console.log(resStudent);
        console.log(req.query);
        res.status(200).json({resStudent, lengthOfStudentList : resStudent.length});
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all students Total and Grade : "+error);
    }
}

module.exports = {
    getAllStudents,
    getAllStudentsByName,
    getAllStudentsByHobbiesGender,
    getAllStudentsByAgeRangeAndHobbies,
    getAllStudentsByAddress,
    getAllStudentsByScienceMarksRange,
    getAllStudentsByTotalGrade,
}

Enter fullscreen mode Exit fullscreen mode

10) write code inside studentsB.js =>

const Student = require("../models/students");
const { calcGradeTotalStudent } = require("../CalculateTotalGrade/calcTotalGrade");

const createNewStudent= async (req,res) => {
        console.log(req.body);  
        try{
                 const studentData = new Student({
                    name : {
                        first : req.body.name.first,
                        last : req.body.name.last,
                    },
                    age : req.body.age,
                    isAlive : req.body.isAlive,
                    gender : req.body.gender,
                    address : {
                        state : req.body.address.state,
                        district : req.body.address.district,
                        city : req.body.address.city,
                    },
                    science : {
                        physics : req.body.science.physics,
                        chemistry : req.body.science.chemistry,
                        mathematics : req.body.science.mathematics,
                    },
                    hobbies : req.body.hobbies,
           });

           calcGradeTotalStudent([studentData]);
           const createStudentData = await studentData.save();
           res.status(201).send(createStudentData);

           console.log(createStudentData);
        }
    catch(error){
        res.status(400).json("something went wrong while getting all the students : "+error);
    } 
}

const updateStudentByName = async (req,res) => {
        try{
            console.log(req.body);
            const {firstName, lastName} = req.query;
            const queryObject = { firstName : "", lastName : ""};

            if(firstName){
                queryObject.firstName = { $regex : firstName , $options : 'i'},
                console.log(queryObject);
                console.log(queryObject.firstName);
            }

            if(lastName){
                queryObject.lastName = { $regex : lastName , $options : 'i'} 
                console.log(queryObject);
                console.log(queryObject.lastName);
            }
            const updateStudent = await Student.findOneAndUpdate({"name.first" : queryObject.firstName , "name.last" : queryObject.lastName}, 
                {$set : req.body },
                 {
                   returnDocument : "after"
                 }
                );
                calcGradeTotalStudent([updateStudent]);
                const resStudent = await updateStudent.save();

              console.log(resStudent);
              res.status(201).send(updateStudent);
        }
        catch(err){
            console.log("Something went wrong while updating the data : "+err);
        }
}

const updateStudentByAddress = async (req,res) => {
    try{
        console.log(req.body);
        const {state, district, city} = req.query;
        const queryObject = { state : "", district : "", city : ""};

        if(state){
            queryObject.state ={ $regex : state , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.state);
        }

        if(district){
            queryObject.district = { $regex : district , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.district);
        }

        if(city){
            queryObject.city = { $regex : city, $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.city);
        }
        const updateStudent = await Student.findOneAndUpdate({"address.state" : queryObject.state,
         "address.district" : queryObject.district, "address.city" : queryObject.city}, 
            {$set : req.body },
             {
               returnDocument : "after"
             }
            );
            calcGradeTotalStudent([updateStudent]);
            const resStudent = await updateStudent.save();

          console.log(resStudent);
          res.status(201).send(updateStudent);
    }
    catch(err){
        console.log("Something went wrong while updating the data : "+err);
    }
}

const deleteStudentByName = async (req,res) => {
    try{
        const {firstName, lastName} = req.query;
        const queryObject = { firstName : "", lastName : ""};

        if(firstName){
            queryObject.firstName = { $regex : firstName , $options : 'i'},
            console.log(queryObject);
            console.log(queryObject.firstName);
        }

        if(lastName){
            queryObject.lastName = { $regex : lastName , $options : 'i'} 
            console.log(queryObject);
            console.log(queryObject.lastName);
        }

        const studentResult = await Student.findOneAndDelete({"name.first" : queryObject.firstName, "name.last" : queryObject.lastName});

        if(!(firstName && lastName)){
           return res.status(404).send("No student is found with this first name and last name !!..");
        }
        console.log(studentResult);
        res.status(201).send(studentResult);   
    }
    catch(err){
      res.status(500).send("Somethething wrong happend in deleting : "+err);
    }
}

// deleteStudentByAddress
const deleteStudentByAddress = async (req,res) => {
    try{
        const {state, district , city} = req.query;
        const queryObject = {};

        if(state){
            queryObject.state ={ $regex : state , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.state);
        }

        if(district){
            queryObject.district = { $regex : district , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.district);
        }

        if(city){
            queryObject.city = { $regex : city, $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.city);
        }

        const studentResult = await Student.findOneAndDelete({"address.state" : queryObject.state, "address.district" : queryObject.district
                                                               , "address.city" : queryObject.city});

        if(!(state && district && city)){
           return res.status(404).send("No student is found with this address !!..");
        }
        console.log(studentResult);
        res.status(201).send(studentResult);  
    }
    catch(err){
      res.status(400).send("Something went Wrong while deleting student by address : !!! "+err);
    }
}

module.exports = {
    createNewStudent,
    updateStudentByName,
    updateStudentByAddress,
    deleteStudentByName,
    deleteStudentByAddress,
}

Enter fullscreen mode Exit fullscreen mode

11) Now come to db folder and craete connect.js file and write code inside it =>


const mongoose = require("mongoose");
// const { options } = require("../routes/products");


const connectDB = (uri) => {
    console.log("Hello , I am inside connectDB function....!!!");
    return mongoose.connect(uri)
}

module.exports = connectDB;

Enter fullscreen mode Exit fullscreen mode

12) Now create a .env file inside MyStudentAPI_1 folder
[ ***notes : go to mongoDB atlas set up your database ]


MONGODB_URL = mongodb+srv://{username}:{password}@{clustername}.jq9vjnd.mongodb.net/MyStudentDB[database name]?retryWrites=true&w=majority

Enter fullscreen mode Exit fullscreen mode

13) The come to calculateGradeTotal folder and create calcTotalGrade.js file and write code inside it =>


const student = require("../models/students");

const calcGradeTotalStudent = (studentData) => {
    let total, avg, dataLength;
    dataLength = studentData.length;

    console.log("Hello , I am calculating Total and Grade ...!!!");
    console.log("Length of student data list = "+dataLength);

    for(var i = 0; i < dataLength ; i++){
        studentData[i].total = studentData[i].science.physics + studentData[i].science.chemistry + studentData[i].science.mathematics;
        total = studentData[i].total;
        avg = total / 3;
        studentData[i].average = avg.toFixed(2); 
        getGradeStudent(studentData,avg,i);
    } 
}

const getGradeStudent = (studentData,avg,ind) => {

     if(avg >= 90){
         studentData[ind].grade = "Excellent";
     }
     else if(avg >= 80 && avg < 90){
         studentData[ind].grade = "Very Good";
     }
     else if(avg >= 70 && avg < 80){
        studentData[ind].grade = "Good";
    }
    else if(avg >= 60 && avg < 70){
        studentData[ind].grade = "Satisfactory";
    }
    else if(avg >= 40 && avg < 60){
        studentData[ind].grade = "Not Good";
    }
    else{
        studentData[ind].grade = "Fail";
    }
}

module.exports = {
    calcGradeTotalStudent
}

Enter fullscreen mode Exit fullscreen mode

14) Now create a file in main folder MyStudentAPI_1 called StudentDB.js =>

const connectDB = require("./src/db/connect");
require("dotenv").config();
const { 
    calcGradeTotalStudent
   }  = require("./src/CalculateTotalGrade/calcTotalGrade");

const Student = require("./src/models/students");
const StudentJson = require("./Students.json");

const startDataBase = async () => {
    try{
        await connectDB(process.env.MONGODB_URL);
       // await Product.deleteMany();
        calcGradeTotalStudent(StudentJson);
        await Student.create(StudentJson);
        console.log("Successfully Documents of students inserted...!!!");
    }
    catch(error){
        console.log("Something went wrong with Databse connection ....!!!"+error);
    }
}

startDataBase();

Enter fullscreen mode Exit fullscreen mode

15) Now create a .json{} file inside MyStudentAPI_1 that is "Students.json{}" and write the code given below =>


[
   {
     "name" : {
        "first" : "Mayuk",
        "last" : "Mukherjee"
    },
    "age" : 24,
    "isAlive" : true,
    "gender" : "Male",
    "address" : {
        "state" : "California",
        "district" : "Denver",
        "city" : "Ohio"
    },
    "science" : {
        "physics" : 99,
        "chemistry" : 88,
        "mathematics" : 97
    },
    "hobbies" : ["Gymming", "Reading", "Travelling", "Painting"]
   },
   {
    "name" : {
        "first" : "Suryendu",
        "last" : "Sarkar"
    },
    "age" : 22,
    "isAlive" : true,
    "gender" : "Male",
    "address" : {
        "state" : "Colorado",
        "district" : "Colorado",
        "city" : "Georgia"
    },
    "science" : {
        "physics" : 86,
        "chemistry" : 81,
        "mathematics" : 92
    },
    "hobbies" : ["Gymming", "Reading", "Singing", "Dancing"]
   },
   {
    "name" : {
        "first" : "Aninda",
        "last" : "Mukherjee"
    },
    "age" : 27,
    "isAlive" : true,
    "gender" : "Male",
    "address" : {
        "state" : "Texas",
        "district" : "Ohio",
        "city" : "Colorado"
    },
    "science" : {
        "physics" : 81,
        "chemistry" : 71,
        "mathematics" : 86
    },
    "hobbies" : ["Gymming", "Travelling", "Singing", "Painting"]
   },
   {
    "name" : {
        "first" : "Snalap",
        "last" : "Gadai"
    },
    "age" : 22,
    "isAlive" : true,
    "gender" : "Male",
    "address" : {
        "state" : "California",
        "district" : "Georgia",
        "city" : "Denver"
    },
    "science" : {
        "physics" : 74,
        "chemistry" : 86,
        "mathematics" : 69
    },
    "hobbies" : ["Blogging", "Cricket", "Dancing", "Reading"]
   },
   {
    "name" : {
        "first" : "Souvik",
        "last" : "Chatterjee"
    },
    "age" : 29,
    "isAlive" : true,
    "gender" : "Male",
    "address" : {
        "state" : "Colorado",
        "district" : "Ohio",
        "city" : "Colorado"
    },
    "science" : {
        "physics" : 66,
        "chemistry" : 58,
        "mathematics" : 84
    },
    "hobbies" : ["Blogging", "Cricket", "Dancing", "Reading"]
   },
   {
    "name" : {
        "first" : "Shreyashi",
        "last" : "Biswas"
    },
    "age" : 19,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "California",
        "district" : "Georgia",
        "city" : "Ohio"
    },
    "science" : {
        "physics" : 86,
        "chemistry" : 74,
        "mathematics" : 64
    },
    "hobbies" : ["Blogging", "Cricket", "Football", "Coocking"]
   },
   {
    "name" : {
        "first" : "Sukalpa",
        "last" : "Das"
    },
    "age" : 38,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Texas",
        "district" : "California",
        "city" : "Denver"
    },
    "science" : {
        "physics" : 56,
        "chemistry" : 78,
        "mathematics" : 94
    },
    "hobbies" : ["Blogging", "Football", "Singing", "Tennis"]
   },
   {
    "name" : {
        "first" : "Sanjukta",
        "last" : "Chatterjee"
    },
    "age" : 32,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Denver",
        "district" : "Colorado",
        "city" : "Colorado"
    },
    "science" : {
        "physics" : 96,
        "chemistry" : 52,
        "mathematics" : 74
    },
    "hobbies" : ["Singing", "Baseball", "Coocking", "Football"]
   },
   {
    "name" : {
        "first" : "Soumi",
        "last" : "Chatterjee"
    },
    "age" : 36,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "California",
        "district" : "Texas",
        "city" : "Ohio"
    },
    "science" : {
        "physics" : 74,
        "chemistry" : 83,
        "mathematics" : 79
    },
    "hobbies" : ["Gymming", "Tennis", "Coocking", "Travelling"]
   },
   {
    "name" : {
        "first" : "Kakan",
        "last" : "Bag"
    },
    "age" : 49,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Denver",
        "district" : "California",
        "city" : "Georgia"
    },
    "science" : {
        "physics" : 88,
        "chemistry" : 72,
        "mathematics" : 69
    },
    "hobbies" : ["Tennis", "Cricket", "Singing", "Reading"]
   },
   {
    "name" : {
        "first" : "Tom",
        "last" : "Cruise"
    },
    "age" : 42,
    "isAlive" : true,
    "gender" : "Male",
    "address" : {
        "state" : "Colorado",
        "district" : "Texas",
        "city" : "Georgia"
    },
    "science" : {
        "physics" : 91,
        "chemistry" : 77,
        "mathematics" : 64
    },
    "hobbies" : ["Blogging", "Gymming", "Dancing", "Baseball"]
   },
   {
    "name" : {
        "first" : "Natlie",
        "last" : "Portman"
    },
    "age" : 46,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Ohio",
        "district" : "Colorado",
        "city" : "Ohio"
    },
    "science" : {
        "physics" : 88,
        "chemistry" : 66,
        "mathematics" : 92
    },
    "hobbies" : ["Reading", "Tennis", "Dancing", "Footbal"]
   },
   {
    "name" : {
        "first" : "Emma",
        "last" : "Stone"
    },
    "age" : 53,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Georgia",
        "district" : "Denver",
        "city" : "Georgia"
    },
    "science" : {
        "physics" : 94,
        "chemistry" : 67,
        "mathematics" : 84
    },
    "hobbies" : ["Blogging", "Gymming", "Coocking", "Singing"]
   },
   {
    "name" : {
        "first" : "Catherine",
        "last" : "Langford"
    },
    "age" : 44,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Ohio",
        "district" : "Colorado",
        "city" : "California"
    },
    "science" : {
        "physics" : 81,
        "chemistry" : 57,
        "mathematics" : 94
    },
    "hobbies" : ["Travelling", "Tennis", "Dancing", "Baseball"]
   },
   {
    "name" : {
        "first" : "Sylvester",
        "last" : "Stellone"
    },
    "age" : 46,
    "isAlive" : true,
    "gender" : "Female",
    "address" : {
        "state" : "Georgia",
        "district" : "Denver",
        "city" : "Ohio"
    },
    "science" : {
        "physics" : 68,
        "chemistry" : 97,
        "mathematics" : 82
    },
    "hobbies" : ["Reading", "Painting", "Coocking", "Footbal"]
   }
]

Enter fullscreen mode Exit fullscreen mode

Now to start your Data base open your terminal and write command like =>

nodemon StudentDB.js
then type ctrl+c

then write command =>

nodemon src/app.js

then to host your api on your localhost at port number 7070
go to web browser and on the url section type links like=>

1) http://localhost:7070/api/students?sort=address.state,science.physics&select=name,address,science,-_id&page=1&limit=15

2) http://localhost:7070/api/students/Name?firstName=lvEsT&lastName=ElLO&sort=address.state&select=name,address,total,grade,-_id

3) http://localhost:7070/api/students/HobbyGender?gender=Female&hobbies=Singing,Football&sort=science.mathematics&select=name,total,-_id,grade,hobbies,gender

4) http://localhost:7070/api/students/AgeHobby?ageMax=35&ageMin=18&hobbies=Reading,Gymming&select=name,age,hobbies,-_id

5) http://localhost:7070/api/students/Address?state=CAliF&district=EOrG&city=ENv&sort=total&select=name,address,total,grade,-_id

6) http://localhost:7070/api/students/Marks?phyMin=75&phyMax=88&chemMin=70&chemMax=80&mathMin=65&mathMax=90&sort=science.mathematics&select=name,science,total,grade,-_id

7) http://localhost:7070/api/students/TotalGrade?totalMin=240&totalMax=290&grade=eRY&sort=science.chemistry&select=name,total,science,average,grade,-_id

Then after that you can also use POST, PATCH, DELTE Requests on POSTMAN =>

I am giving screen shots please follow that =>

POST Request

PATCH Request

PATCH Request

DELTE Request

DELETE Request

Top comments (1)

Collapse
 
swapnanilwebdeveloper profile image
swapnanilWebDeveloper

Hello , programmers I am here to help you become a better programmer . I have given the full details of this API here on this post but still if you coders face any problem understanding the concept or any difficulties , you can always come to ask me your doubt. Do not hesitate to comment your doubt on this post ...... and let me help you in your programming journey...