REST APIs By Express,Node,MongoDB Atlas,Mongoose#CRUD operation in API
Tags: webdev, javascript, beginners, api
Published: 2024-02-24 09:45:12

1) It is very important to Build your own API. Building your own API can boost your Full stack project.

2)When ever you are creating a full stack project then you need an API to provide data to your front-end app.

3)If you are not able to create your own API then you will be dependent on the Mock APIs that are available on google .

4)Some times this APIs are not accurately relevant to the project You are building right now.

5)If you want to fulfill your project with proper API then you need to create your API by Express that will be perfectly suited to your project.

6)To build your own API you will need Express.js, Node.js, MongoDB Atlas or MongoDB compass and Mongoose.

7)Here in this article I will guide you step by step how to build your Own RestFul API.

8) To get the full code click on my git repository link

[click to get full code](https://github.com/swapnanilWebDeveloper/Express_API_Movie_1)

9) I have hosted this API on render also =>

[click to get API](https://express-api-movie-1.onrender.com/api/movies/genre?genre=Action,Adventure,ScienceFiction&select=title,releaseYear,ratings,genre,-_id)

Step-1 : Folder structure
  a) Create A folder called MyMoviesAPI_1

  b) Create another folder inside it called src

  c) Then install packages => inside main folder MyMoviesAPI_1
     npm install express
     npm install mongoose
     npm install dotenv 
     npm install mongodb

 d) create folder controllers,db,models,routes,VerdictPrediction
    inside the folder src.

 e) Then go to package.json file and write => 
```javascript
     "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/app.js"
  },
```
step-2: 
a) Create a file called app.js inside src
b) Now write code inside that app.js file like =>

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

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

const movies_routes  = require("./routes/movies");

app.use(express.json());

app.get("/", (req, res) => {
    res.send("Hello programmer is live from the home page .....!!!");
});

// middleware or to set router
app.use("/api/movies", movies_routes);

const LiveStudentConnection = async (req,res) => {
    try{
        const res = await connectDB(process.env.MONGODB_URL);
          if(res){
            console.log("Connection successfull !! ");
           }
          else{
            console.log("Somwthing wrong with Connection to Database...");
          }
         app.listen(PORT, () => {
         console.log(`Port number : ${PORT} , Yes I am connected !!`);
       });
    }
    catch(err){
      console.log("Something went wrong at listening to port : "+PORT+" !!! : "+err);
    }
 }
 
 LiveStudentConnection();
```
step-3:
a)Inside db folder create file connect.js

b) Here you have to write the code as I give you below

```javascript
const mongoose = require("mongoose");
const { options } = require("../routes/movies");


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

module.exports = connectDB;

```
step-3 :
a) Now create a file MovieDB.js inside src folder 
b) Then write the code given below => 

```javascript
const connectDB = require("./src/db/connect");
require("dotenv").config();

const Movie = require("./src/models/movies");
const MovieJson = require("./Movies.json");

const CalculateVerdict = require("./src/VerdictPrediction/calcVerdict");

let len = MovieJson.length;
console.log("Number of movies are = "+len);

for(var i = 0; i < len; i++){
    CalculateVerdict(MovieJson[i]);
}

const start = async () => {
    try{
        await connectDB(process.env.MONGODB_URL);
       // await Product.deleteMany();
        await Movie.create(MovieJson);
        console.log("Documents of movies inserted, Successfully ...!!!");
    }
    catch(error){
        console.log("Something went wrong with Databse connection ....!!!"+error);
    }
}

start();

```
step-4 :
a)Then create another file Movies.json

b)Here in the .json{} file you will have to give data of multiple movies that will be inserted into your database in one go.

c) Then give the code as written below

```javascript
[
    {
        "title" : "Beauty and the Beast",
        "releaseYear" : 2017,
        "rated" : "PG",
        "durationMinute" : 129,
        "genre" : ["Adventure", "Family", "Fantasy"],
        "ratings" : {
            "IMDB" :  7.1,
            "Metascore" : 65
        },
        "featured" : true,
        "director" :  "Bill Condon",
        "starCast" : ["Emma Watson", "Dan Stevens", "Luke Evans", "Josh Gad"],
        "votes" : 331952,
        "NumbersInCount" : {
            "grossCollection" : 504.01,
            "budget" : 254
        }
    },
    {
        "title" : "Logan",
        "releaseYear" : 2017,
        "rated" : "R",
        "durationMinute" : 137,
        "genre" : ["Action", "Drama", "ScienceFiction"],
        "ratings":{
            "IMDB" :  8.1,
            "Metascore" : 77
        },
        "featured" : true,
        "director" :  "James Mangold",
        "starCast" : ["Hugh Jackman", "Patrick Stewart", "Dafne Keen", "Boyd Holdbrook"],
        "votes" : 821852,
        "NumbersInCount" : {
            "grossCollection" : 226.28,
            "budget" : 97
        }
    },
    {
        "title" : "X-Men : Apocalypse",
        "releaseYear" : 2016,
        "rated" : "PG-13",
        "durationMinute" : 144,
        "genre" : ["Action", "Adventure", "ScienceFiction"],
        "ratings":{
            "IMDB" :  6.9,
            "Metascore" : 52
        },
        "featured" : true,
        "director" :  "Bryan Singer",
        "starCast" : ["James McAvoy", "Michael Fassbender", "Jennifer Lawrence", "Nicholas Hoult"],
        "votes" : 457705,
        "NumbersInCount" : {
            "grossCollection" : 543.9,
            "budget" : 178
        }
    },
    {
        "title" : "Deadpool",
        "releaseYear" : 2016,
        "rated" : "R",
        "durationMinute" : 108,
        "genre" : ["Action", "Comedy"],
        "ratings":{
            "IMDB" :  8.0,
            "Metascore" : 65
        },
        "featured" : true,
        "director" :  "Tim Miller",
        "starCast" : ["Ryan Reynolds", "Morena Baccarin", "T.J Miller", "ED Skrein"],
        "votes" : 1112702,
        "NumbersInCount" : {
            "grossCollection" : 363.07,
            "budget" : 58
        }
    },
    {
        "title" : "Man of Steel",
        "releaseYear" : 2013,
        "rated" : "PG-13",
        "durationMinute" : 143,
        "genre" : ["Action", "Adventure", "ScienceFiction"],
        "ratings":{
            "IMDB" :  7.1,
            "Metascore" : 55
        },
        "featured" : true,
        "director" :  "Zack Snyder",
        "starCast" : ["Henry Cavil", "Amy Adams", "Michael Shannon", "Diane Lane"],
        "votes" : 807519,
        "NumbersInCount" : {
            "grossCollection" : 668,
            "budget" : 225
        }
    },
    {
        "title" : "Batman v Superman : Dawn of Justice",
        "releaseYear" : 2016,
        "rated" : "PG-13",
        "durationMinute" : 151,
        "genre" : ["Action", "Adventure", "ScienceFiction"],
        "ratings":{
            "IMDB" :  6.5,
            "Metascore" : 44
        },
        "featured" : true,
        "director" :  "Zack Snyder",
        "starCast" : ["Ben Affleck", "Henry Cavil", "Amy Adams", "Jessy Einsberg"],
        "votes" : 748731,
        "NumbersInCount" : {
            "grossCollection" : 873.6,
            "budget" : 250
        }
    },
    {
        "title" : "Slumdog Milionaire",
        "releaseYear" : 2008,
        "rated" : "R",
        "durationMinute" : 120,
        "genre" : ["Crime", "Drama", "Romance"],
        "ratings":{
            "IMDB" :  8.0,
            "Metascore" : 84
        },
        "featured" : true,
        "director" :  "Danny Boyle",
        "starCast" : ["Dev Patel", "Freida Pinto", "Saurabh Sukla", "Anil Kapoor"],
        "votes" : 873576,
        "NumbersInCount" : {
            "grossCollection" : 377.9,
            "budget" : 15
        }
    },
    {
        "title" : "Titanic",
        "releaseYear" : 1997,
        "rated" : "PG-13",
        "durationMinute" : 194,
        "genre" : ["Drama", "Romance"],
        "ratings":{
            "IMDB" :  7.9,
            "Metascore" : 75
        },
        "featured" : true,
        "director" :  "James Cameron",
        "starCast" : ["Leonardo De Caprio", "Kate Winslet", "Billy Zane", "Kathy Bates"],
        "votes" : 1269409,
        "NumbersInCount" : {
            "grossCollection" : 600.78,
            "budget" : 200
        }
    },
    {
        "title" : "Avatar",
        "releaseYear" : 2009,
        "rated" : "PG-13",
        "durationMinute" : 162,
        "genre" : ["Action", "Adventure", "Fantasy"],
        "ratings":{
            "IMDB" :  7.9,
            "Metascore" : 83
        },
        "featured" : true,
        "director" :  "James Cameron",
        "starCast" : ["Sam Warthington", "Zoe Saldana", "Sigourney Weaver", "Michell Rodriguez"],
        "votes" : 1376466,
        "NumbersInCount" : {
            "grossCollection" : 2920,
            "budget" : 237
        }
    },
    {
        "title" : "Gravity",
        "releaseYear" : 2013,
        "rated" : "PG-13",
        "durationMinute" : 91,
        "genre" : ["Drama", "ScienceFiction", "Thriller"],
        "ratings":{
            "IMDB" :  7.7,
            "Metascore" : 96
        },
        "featured" : true,
        "director" :  "Alfonso Cuaron",
        "starCast" : ["Sandra Bullock", "George Clooney", "Ed Harris", "Orto Ignatiussen"],
        "votes" : 858587,
        "NumbersInCount" : {
            "grossCollection" : 723.19,
            "budget" : 100
        }
    },
    {
        "title" : "The Dark Knight",
        "releaseYear" : 2008,
        "rated" : "PG-13",
        "durationMinute" : 152,
        "genre" : ["Action", "Crime", "Drama"],
        "ratings":{
            "IMDB" :  9,
            "Metascore" : 84
        },
        "featured" : true,
        "director" :  "Chirstopher Nolan",
        "starCast" : ["Christian Bell", "Heath Ledger", "Aron Eckhart", "Michael Caine"],
        "votes" : 2841462,
        "NumbersInCount" : {
            "grossCollection" : 1006,
            "budget" : 185
        }
    },
    {
        "title" : "The Dark Knight Rises",
        "releaseYear" : 2012,
        "rated" : "PG-13",
        "durationMinute" : 164,
        "genre" : ["Action", "Drama", "erer"],
        "ratings":{
            "IMDB" :  8.4,
            "Metascore" : 78
        },
        "featured" : true,
        "director" :  "Chirstopher Nolan",
        "starCast" : ["Christian Bell", "Tom Hardy", "Anny Hataway", "Gary Oldman"],
        "votes" : 1810265,
        "NumbersInCount" : {
            "grossCollection" : 1085,
            "budget" : 250
        }
    },
    {  
        "title" : "Batman Begins",
        "releaseYear" : 2005,
        "rated" : "PG-13",
        "durationMinute" : 140,
        "genre" : ["Action", "Crime", "Drama"],
        "ratings":{
            "IMDB" :  8.2,
            "Metascore" : 70
        },
        "featured" : true,
        "director" :  "Chirstopher Nolan",
        "starCast" : ["Christian Bell", "Michael Caine", "Ken Watanabe", "Liam Neeson"],
        "votes" : 1564017,
        "NumbersInCount" : {
            "grossCollection" : 373.7,
            "budget" : 150
        }
    },
    {
        "title" : "Gurdians of the Galaxy",
        "releaseYear" : 2014,
        "rated" : "PG-13",
        "durationMinute" : 121,
        "genre" : ["Action", "Adventure", "Comedy"],
        "ratings":{
            "IMDB" :  8.0,
            "Metascore" : 76
        },
        "featured" : true, 
        "director" :  "James Gunn",
        "starCast" : ["Chris Patt", "Vin Diesel", "Bradley Cooper", "Zoe Saldana"],
        "votes" : 1263708,
        "NumbersInCount" : {
            "grossCollection" : 333.18,
            "budget" : 79.84
        }
    },
    {
        "title" : "Captain America: Civil War",
        "releaseYear" : 2016,
        "rated" : "PG-13",
        "durationMinute" : 147,
        "genre" : ["Action", "ScienceFiction"],
        "ratings":{
            "IMDB" :  7.8,
            "Metascore" : 75
        },
        "featured" : true,
        "director" :  "Anthony Russo",
        "starCast" : ["Chris Evans", "Robert Downey Jr.", "Scarlett Johansson", "Sebastian Stan"],
        "votes" : 842986,
        "NumbersInCount" : {
            "grossCollection" : 1153.3,
            "budget" : 250
        }
    }
]

```
step-5 : 
a) Here we will discuss about the .env file and MongoDB Atlas

b) GO to mongoDB Atlas and create your own project , cluster, then go to DataBase and click on connect then click on drivers
then you will get a sample URL like => 

mongodb+srv://username:<password>@clusterName.uiiembe.mongodb.net/DatabaseName{write your database name here}?retryWrites=true&w=majority

my Database name is MovieDB.

c)Now come to your Visual studio code and inside .env file write code like => 
```javascript

MONGODB_URL = mongodb+srv://username:<password>@clusterName.uiiembe.mongodb.net/DatabaseName{write your database name here}?retryWrites=true&w=majority

```
d) Then inside terminal write command node MovieDb.js

step-6:
a) Inside the folder routes create files => movies.js

b) Write code like => 

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

const {
    getAllMoviesPaginationLimit,
    getAllMoviesBySortSelect,
    getAllMoviesByTitle, // regular expression // single request params
    getAllMoviesByDirector, // regular expression // single request params
    getAllMoviesByStarCast, // regular expression // single request params
    getAllMoviesByMultiStarCast, // array $all operator // single request params
    getAllMoviesByGenre, // array in element and regular expression // single request params
    
} = require("../controllers/moviesA");

const {
    getAllMoviesByReleaseYearRange, // and // double request params
    getAllMoviesByIMDBRatingRange, // and // double request params
    getAllMoviesByMetaScoreRatingRange, // and // double request params
    getAllMoviesByGrossCollection, //and // double request params
    getAllMoviesByBudget, // and // double request params
} = require("../controllers/moviesB");

const {
    getAllMoviesByRatedAndStarCast, // AND // multiple request params
    getAllMoviesByDirectorAndStarCast, // 1. reg Expression AND, 2.array in element // // multiple request params
    getAllMoviesByGenreAndStarCast, // 1. reg Expression AND, 2.array in element // // multiple request params  
} = require("../controllers/moviesC");

const {
    createNewMovie,
    updateMovieByTitle,
    deleteMovieByDirector,
} = require("../controllers/moviesD");

router.route("/").get(getAllMoviesPaginationLimit);
router.route("/sortProject").get(getAllMoviesBySortSelect);
router.route("/title").get(getAllMoviesByTitle);
router.route("/director").get(getAllMoviesByDirector);
router.route("/starCast").get(getAllMoviesByStarCast);
router.route("/multiStarCast").get(getAllMoviesByMultiStarCast);
router.route("/genre").get(getAllMoviesByGenre);

router.route("/releaseYear").get(getAllMoviesByReleaseYearRange);
router.route("/IMDBRating").get( getAllMoviesByIMDBRatingRange);
router.route("/MetaScoreRating").get(getAllMoviesByMetaScoreRatingRange);
router.route("/GrossCollection").get(getAllMoviesByGrossCollection);
router.route("/Budget").get(getAllMoviesByBudget);

router.route("/RatedAndStarCast").get(getAllMoviesByRatedAndStarCast);
router.route("/DirectorAndStarCast").get(getAllMoviesByDirectorAndStarCast);
router.route("/GenreAndStarCast").get(getAllMoviesByGenreAndStarCast);

router.route("/createMovie").post(createNewMovie);
router.route("/updatebytitle").patch(updateMovieByTitle);
router.route("/deletebydiredctor").delete(deleteMovieByDirector);

module.exports = router;

```
step-7:
a) Come to controllers create four Files moviesA.js, moviesB.js, moviesC.js, moviesD.js

```javascript
 const Movie = require("../models/movies");

const getAllMoviesPaginationLimit = async (req,res) => {
    try{
        let page = Number(req.query.page) || 1;
        let limit = Number(req.query.limit) || 3;

        let MovieData = Movie.find();

        let skip = (page - 1) * limit ;

        MovieData = MovieData.skip(skip).limit(limit);

        const resMovie = await MovieData;
        console.log(resMovie);
        res.status(200).json({resMovie,ListMovieslength : resMovie.length});
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all products : "+error);
    }
}

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

        console.log(sort);
        let MovieData = Movie.find(); 

        if(sort){
            let sortFix = sort.replaceAll(",", " ");
            console.log(sortFix);
            MovieData = MovieData.sort(sortFix);
        }

        if(select){
            let selectFix = select.replaceAll(",", " ");
            console.log(select);
            console.log(selectFix);
            MovieData = MovieData.select(selectFix);
        }

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

        let skip = (page - 1) * limit ;

        MovieData = MovieData.skip(skip).limit(limit);

        const resMovie = await MovieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, lengthOfMyData : resMovie.length});
    }
    catch(error){
        res.status(400).json("something went wrong while testing the data : "+error);
    }
}

// get all movies by title
const getAllMoviesByTitle = async (req,res) => {
    try{
        const {title,select} = req.query;
        const queryObject = {};

        let MovieData = Movie.find();

        if(title){
            queryObject.title = { $regex : title , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.title);
            MovieData = MovieData.find(queryObject);
        }
        
        if(select){
            let selectFix = select.replaceAll(",", " ");
            console.log(select);
            console.log(selectFix);
            MovieData = MovieData.select(selectFix);
        }

        const resMovie = await MovieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by title : "+error);
    }
}

// get all movies by Director
const getAllMoviesByDirector = async (req,res) => {
    try{
        const {director,select} = req.query;
        const queryObject = {};

        let MovieData = Movie.find();

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

        if(select){
            let selectFix = select.replaceAll(",", " ");
            console.log(select);
            console.log(selectFix);
            MovieData = MovieData.select(selectFix);
        }

        const resMovie = await MovieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by director : "+error);
    }
}

// get all movies by StarCast
const getAllMoviesByStarCast = async (req,res) => {
    try{
        const {starCast,select} = req.query;
        const queryObject = {};

        let MovieData = Movie.find();

        if(starCast){
            queryObject.starCast = { $regex : starCast , $options : 'i'};
            console.log(queryObject);
            console.log(queryObject.starCast);
            MovieData = MovieData.find({starCast : { $elemMatch : queryObject.starCast } });
        }
        
        if(select){
            let selectFix = select.replaceAll(",", " ");
            console.log(select);
            console.log(selectFix);
            MovieData = MovieData.select(selectFix);
        }

        const resMovie = await MovieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by star cast : "+error);
    }
}

// get all movies by multi star cast
const getAllMoviesByMultiStarCast = async (req,res) => {
    try{
        const {starCast,select} = req.query;
        const queryObject = {};

        let MovieData = Movie.find();

        if(starCast){
            let starCastArr = starCast.split(",");
            console.log(starCastArr);
            queryObject.starCast = starCastArr;
            console.log(queryObject);
            console.log(queryObject.starCast);
            MovieData = MovieData.find({starCast : { $all : queryObject.starCast } });
        }
        
        if(select){
            let selectFix = select.replaceAll(",", " ");
            console.log(select);
            console.log(selectFix);
            MovieData = MovieData.select(selectFix);
        }

        const resMovie = await MovieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by genre : "+error);
    }
}

const getArrayMovieInformatrion = ( movie_info ) =>{
    const segmenter = new Intl.Segmenter([], { granularity: 'word' });
    const segmentedGenre = segmenter.segment(movie_info);
    const words = [...segmentedGenre].filter(s => s.isWordLike).map(s => s.segment);
    console.log(words)
    return words;
}

// get all movies by Genre
const getAllMoviesByGenre = async (req,res) => {
    try{
        const {genre,select} = req.query;
        const queryObject = {};

        let MovieData = Movie.find();

        if(genre){
            // console.log(genre);
            let genreArr = getArrayMovieInformatrion(genre);
            console.log(genreArr);
            queryObject.genre = genreArr;
            console.log(queryObject);
            console.log(queryObject.genre);
            MovieData = MovieData.find({genre : { $all : queryObject.genre } });
        }
        
        if(select){
            let selectFix = select.replaceAll(",", " ");
            console.log(select);
            console.log(selectFix);
            MovieData = MovieData.select(selectFix);
        }

        const resMovie = await MovieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by genre : "+error);
    }
}

module.exports = { 
    getAllMoviesPaginationLimit,
    getAllMoviesBySortSelect,
    getAllMoviesByTitle,
    getAllMoviesByDirector,
    getAllMoviesByStarCast,
    getAllMoviesByGenre,
    getAllMoviesByMultiStarCast,
}

```

step-8 : 
a)Inside moviesB.js

```javascript
const Movie = require("../models/movies");

const getAllMoviesByReleaseYearRange = async (req,res) => {
    try{
        const {max,min,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(max){
            queryObject.max = max;
            console.log(queryObject);
            console.log(queryObject.max);
            movieData = movieData.where("releaseYear").lte(max);
        }

        if(min){
            queryObject.min = min;
            console.log(queryObject);
            console.log(queryObject.min);
            movieData = movieData.where("releaseYear").gte(min);
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all products : "+error);
    }
}

const getAllMoviesByIMDBRatingRange = async (req,res) => {
    try{
        const {max,min,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(max){
            queryObject.max = max;
            console.log(queryObject);
            console.log(queryObject.max);
            movieData = movieData.where("ratings.IMDB").lte(max);
        }

        if(min){
            queryObject.min = min;
            console.log(queryObject);
            console.log(queryObject.min);
            movieData = movieData.where("ratings.IMDB").gte(min);
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by IMDB ratings : "+error);
    }
}

const getAllMoviesByMetaScoreRatingRange = async (req,res) => {
    try{
        const {max,min,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(max){
            queryObject.max = max;
            console.log(queryObject);
            console.log(queryObject.max);
            movieData = movieData.where("ratings.Metascore").lte(max);
        }

        if(min){
            queryObject.min = min;
            console.log(queryObject);
            console.log(queryObject.min);
            movieData = movieData.where("ratings.Metascore").gte(min);
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by Metascore ratings : "+error);
    }
}

const getAllMoviesByGrossCollection = async (req,res) => {
    try{
        const {max,min,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(max){
            queryObject.max = max;
            console.log(queryObject);
            console.log(queryObject.max);
            movieData = movieData.where("NumbersInCount.grossCollection").lte(max);
        }

        if(min){
            queryObject.min = min;
            console.log(queryObject);
            console.log(queryObject.min);
            movieData = movieData.where("NumbersInCount.grossCollection").gte(min);
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by Gross collection : "+error);
    }
}

const  getAllMoviesByBudget = async (req,res) => {
    try{
        const {max,min,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(max){
            queryObject.max = max;
            console.log(queryObject);
            console.log(queryObject.max);
            movieData = movieData.where("NumbersInCount.budget").lte(max);
        }

        if(min){
            queryObject.min = min;
            console.log(queryObject);
            console.log(queryObject.min);
            movieData = movieData.where("NumbersInCount.budget").gte(min);
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all movies by budget : "+error);
    }
}

module.exports = {
    getAllMoviesByReleaseYearRange, 
    getAllMoviesByIMDBRatingRange, 
    getAllMoviesByMetaScoreRatingRange, 
    getAllMoviesByGrossCollection,
    getAllMoviesByBudget, 
}
```
step-9:
a)Now inside moviesC.js write code =>

```javascript
const Movie = require("../models/movies");

const getAllMoviesByRatedAndStarCast = async (req,res) => {
    try{
        const {rated,starCast,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(rated){
            queryObject.rated = rated;
            console.log(queryObject);
            console.log(queryObject.rated);
            movieData = movieData.find(queryObject);
        }

        if(starCast){
            let starCastArr = starCast.split(",");
            console.log(starCastArr);
            queryObject.starCast = starCastArr;
            console.log(queryObject);
            console.log(queryObject.starCast);
            movieData = movieData.find({starCast : { $all : queryObject.starCast } });
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all products : "+error);
    }
}

const getAllMoviesByDirectorAndStarCast = async (req,res) => {
    try{
        const {director,starCast,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(director){
            queryObject.director = director;
            console.log(queryObject);
            console.log(queryObject.director);
            movieData = movieData.find(queryObject);
        }

        if(starCast){
            let starCastArr = starCast.split(",");
            console.log(starCastArr);
            queryObject.starCast = starCastArr;
            console.log(queryObject);
            console.log(queryObject.starCast);
            movieData = movieData.find({starCast : { $all : queryObject.starCast } });
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all products : "+error);
    }
}

const getAllMoviesByGenreAndStarCast = async (req,res) => {
    try{
        const {max,min,select} = req.query;
        const queryObject = {};

        let movieData = Movie.find();

        if(max){
            queryObject.max = max;
            console.log(queryObject);
            console.log(queryObject.max);
            movieData = movieData.where("releaseYear").lte(max);
        }

        if(min){
            queryObject.min = min;
            console.log(queryObject);
            console.log(queryObject.min);
            movieData = movieData.where("releaseYear").gte(min);
        }

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

        const resMovie = await movieData;
        console.log(resMovie);
        console.log(req.query);
        res.status(200).json({resMovie, moviesLength : resMovie.length})
    }
    catch(error){
        res.status(400).send("Something went wrong while getting all products : "+error);
    }
} 

module.exports = {
    getAllMoviesByRatedAndStarCast,
    getAllMoviesByDirectorAndStarCast,
    getAllMoviesByGenreAndStarCast
}

```
ste-9 :
a) Now inside MovieD.js write =>

```javascript
const Movie = require("../models/movies");

const CalculateVerdict = require("../VerdictPrediction/calcVerdict");

const createNewMovie = async (req,res) => {
    console.log(req.body);  
    try{
          console.log("creating a new movie...!!!");
            const movieData = new Movie({ 
                title : req.body.title,
                releaseYear :req.body.releaseYear,
                rated : req.body.rated,
                durationMinute : req.body.durationMinute,
                genre : req.body.genre,
                ratings :{
                    IMDB :  req.body.ratings.IMDB,
                    Metascore : req.body.ratings.Metascore,
                }, 
                featured : req.body.featured,
                director :  req.body.director,
                starCast : req.body.starCast,
                votes : req.body.votes,
                NumbersInCount : {
                    grossCollection : req.body.NumbersInCount.grossCollection,
                    budget : req.body.NumbersInCount.budget,
                } 
             });
             CalculateVerdict(movieData);
            const resMovie = await movieData.save();
            res.status(201).send(resMovie);

       console.log("title is = "+req.body.title+", releaseYear = "+movieData.releaseYear+
                "\n director is = "+req.body.director+", starCast = "+movieData.starCast+
                "\n genre is = "+movieData.genre+", budget = $ "+movieData.NumbersInCount.budget+" USD , gross collection = $ "
                 +movieData.NumbersInCount.grossCollection+" USD");
    }
    catch(err){
       res.status(404).send("Something went wrong : !! "+err);
    }
}


// UPDATE movies by StarCast
const updateMovieByTitle = async (req,res) => {
    try{
        const {title} = req.query;
        const queryObject = {};

        if(title){
            queryObject.title = title;
            console.log(queryObject);
            console.log(queryObject.title);
        }

        const updateMovie = await Movie.findOneAndUpdate(queryObject, 
            {$set : 
               { 
                title : req.body.title,
                releaseYear :req.body.releaseYear,
                rated : req.body.rated,
                durationMinute : req.body.durationMinute,
                genre : req.body.genre,
                ratings :{
                    IMDB :  req.body.ratings.IMDB,
                    Metascore : req.body.ratings.Metascore,
                }, 
                featured : req.body.featured,
                director :  req.body.director,
                starCast : req.body.starCast,
                votes : req.body.votes,
                NumbersInCount : {
                    grossCollection : req.body.NumbersInCount.grossCollection,
                    budget : req.body.NumbersInCount.budget,
                },
               } 
            },
             {
               returnDocument : "after"
             }
            );

        CalculateVerdict(updateMovie);
        const resMovie = await updateMovie.save();
        console.log(resMovie);
        res.status(200).send(resMovie);
    }
    catch(error){
        res.status(400).send("Something went wrong while updating movie by title : "+error);
    }
}

const deleteMovieByDirector =  async (req,res) => {
    try{
        const {director} = req.query;
        const queryObject = {};

        if(director){
            queryObject.director = director;
            console.log(queryObject);
            console.log(queryObject.director);
        }

     const movieResult = await Movie.findOneAndDelete(queryObject);
        if(!director){
           return res.status(404).send("No director is found with this name !!..");
        }
        res.status(201).send(movieResult);   
    }
    catch(err){
      res.status(500).send("Somethething wrong happend in deleting : "+err);
    }
}

module.exports = {
    createNewMovie,
    updateMovieByTitle,
    deleteMovieByDirector,
}


```
step-10 : 
a) Then Go to models folder and create a file movies.js
b) Here we will create a Schema and Model =>

```javascript

const mongoose = require("mongoose");

const movieSchema = new  mongoose.Schema({
    title : {
        type : String,
        required : true,
    },
    releaseYear : {
       type : Number,
       default : 2020,
    },
    rated : {
        type : String,
        required : true,
        enum : {
            values : ["R", "PG-13", "PG", "Not Rated", "TV-G"],
            message : `${this.values} is not supported`,
        }
    },
    durationMinute : {
        type : Number,
        required : [true, "PLease give the duration of movie ...!!!"],
    },
    genre : [String],
    ratings : {
        IMDB : {
            type : Number,
            required : [true, "IMDB rating must be provided ...!!!"],
        },
        Metascore : {
            type : Number,
            default : 55,
        },
    },
    featured : {
        type : Boolean,
        default : false,
    },
    director : {
        type : String,
        required : true,
    },
    starCast : [String],
    votes : {
        type : Number,
        required : true,
    },
    NumbersInCount : {
        grossCollection : {
            type : Number,
            required : true,
        }, 
        budget : {
            type : Number,
            required : true,
        },
    },
    verdict : {
        type : String,
        default : "flop",
        enum : {
            values : ["disaster", "flop", "semi-hit", "hit", "super-hit", "all time block buster"],
            message : `${this.values} is not appropiate`,
        }
    },
});

const Movie = mongoose.model('Movie', movieSchema);

module.exports = Movie;

```
step-11 :
a) Then goto Folder VerdictPrediction and then create a file 
   calcVerdict.js
b) Here you will create a function where you will define the value of the property "verdict".

c) Write the code as i Give here below =>

```javascript

function CalculateVerdict(movie){
    let grsClt = movie.NumbersInCount.grossCollection;
    let bgt = movie.NumbersInCount.budget;
    let ratio = (grsClt / bgt).toFixed(1);
    
    if(ratio >= 4.5){
       movie.verdict = "all time block buster";
    }
    else if((ratio >= 3.5 && ratio < 4.5)){
      movie.verdict = "super-hit";
    }
    else if((ratio >= 2.5 && ratio < 3.5)){
     movie.verdict = "hit";
   }
   else if((ratio >= 1.5 && ratio < 2.5)){
     movie.verdict = "semi-hit";
   }
   else if((ratio >= 1.2 && ratio < 1.5)){
     movie.verdict = "flop";
   }
   else{
     movie.verdict = "disaster";
   }  
}

module.exports = CalculateVerdict;

```
Now finally you have to write two commands =>

1) nodemon MovieDb.js
2) ctrl+c 
3) cls
{//Goto your Atlas and check your database that all the data inside json file has been inserted or not....}
2) nodemon src/app.js
5) Now you have a local host of port number 6060 and here is your API hosting on web-browser

links =>
1) http://localhost:6060/api/movies?page=1&limit=15

2) http://localhost:6060/api/movies/sortProject?sort=NumbersInCount.budget,-title&select=ratings,NumbersInCount,-_id,title,director,verdict,releaseYear&page=1&limit=15

3) http://localhost:6060/api/movies/title?title=Descendants&select=title,director,releaseYear,-_id,verdict,ratings&page=1&limit=15

4) http://localhost:6060/api/movies/director?director=Kenny%20Or&select=ratings,title,releaseYear,director,-_id,starCast,genre

5) http://localhost:6060/api/movies/multiStarCast?starCast=Booboo%20Stewart,Dove%20Cameron&select=title,director,starCast,-_id,releaseYear

6) http://localhost:6060/api/movies/genre?genre=Family,Fantasy,Comedy&select=title,releaseYear,ratings,genre,-_id

step-12 : 
a) Now goto postman and do 
   POST , GET, PATCH, DELETE request