Implement Search, Sort, Filter and Pagination Rest API With Node JS | Express | MongoDB - read the full article about Node Js update, Web Development and from CyberWolves on Qualified.One
whats up guys welcome to my channel today were gonna be building this awesome project with mern stack by building this project youre gonna learn how to create api which handle pagination sort filter and search yes all this in one api and we also gonna learn how to call this api and show the data in beautiful ui from front end so why do we need to build api like this because by adding search filter with pagination makes it easier for the user to find what he is looking i am so excited to build this project for you guys i hope you too i recommend you to have basic knowledge of node and react for building this project before we jump into our vs code those who new to this channel i highly recommend you to subscribe and like this video so without wasting time lets get started first open up a command prompt in your computer then create a folder named imdb clone after creating this folder navigate into it inside this folder create server folder where we write all our backend code lets initialize server folder with npm with default values after initializing lets install dependencies we need in this project which are express mongoose dotenv cors and nodemon after installing dependencies open this project in vs code with this command ok now we are in vs code first open package.json file change main file to be server.js inside scripts remove test command and add start command to be nodemon server.js after making changes save this file in root directory create file named server.js inside this file import dot env module then import express module and also import course module first save express instance in app variable were gonna use express.json and cors define port variable its value can be port defined in environment or 8080 then we gonna listen our app on port and console.log save this file and create dot env file in root directory in this file add your mongodb url after adding url save this file and create dbconnect.js file in root directory in this file import mongoose module then create arrow function name db connect and dont forget to export inside this function add connection params variable which will be use new url parser to be true with mongoose.connect method we will connect to our database it required two params database url and connection params on connected event we will console log connected to database successfully on error event we console log error occurred while connecting to database and we also console log error on disconnected event we will console log mongodb connection disconnected thats it guys save this file and open server.js file here import dbconnect file and call the function so that we can connect to our database save this file now lets create models folder in root directory inside that folder create movie.js file in this file import mongoose module we gonna create schema for our movie model which define structure of document default values validators and etc so define movie schema variable and assign new mongoose.schema inside that object add name type will be string and required to be true exactly like that we need image type will be string and year type will be number and genre type will be array of strings and rating type will be number lets create model with help of mongoose.model method it required two params model name and schema then export the model save this file now and create routes folder in root directory inside that folder create movies.js file ok now we gonna write our api which handle pagination search filter and sort so first import router from express module then import movie model from models folder its going to be a get api so add router.get method with endpoint /movies its going to be async function and add try catch block in it if error occurred we console log and send response with 500 status code before we write our code in try block first export this router because i forgot to export most of time let me know in comments is there anyone like me ok after exporting. In try block define page variable and assign page number vc from query by subtracting with 1 if not received it will be 0 you might be thinking why i am taking 0 for page 1 just wait you will understand define limit variable and assign query limit or default limit will be 5 then define search if search query not received assign empty string then define sort and assign query if not received default sort will be rating exactly like sort define genre if not received default will be all in order to filter movies by genre we need all genres we have in our database it is just a demo so i am adding genres manually in an array in real world scenario you should save all genres in a database and get data from there so after getting all genres then if genre is all we assign our genre options array else we split the genre query with comma then if sort query received exactly like genre we split them with comma and assigned to sort else we add sort in an array next we define sort by variable with empty object why we need this because we also gonna allow user to sort rating or year in ascending or descending order so if sort length is greater than 1 it means user has specified in which order he wants so assign sort order to be sort of index 1. here we are taking first element of sort array as dynamic property else default sort will be ascending now define movie variable and add await movie.find inside that add regex and search variable options is i which means case sensitive it matches every letter doesnt matter its capital or small add one more method where to chain. It filters genres by given genres then add sort and pass sort by variable and add skip method here we need to specify how many documents we want to skip it will be page multiply by limit lets assume its page 1 so it will be 0 in back end 0 multiply by 5 which is default limit 5 here we skip 0 documents that is what we want but for second page we skip five documents i hope now you understand why we set it to be zero then dont forget to add limit method which limit documents thats it we got our movies but in order to show how many pages we have we need to do the same query we thought limit after getting total save it in a variable define response variable and add error to be false, total, page, limit, genres so that we can show all genres on frontend and movies then send response with status code of 200.
thats it save this file now and open server.js file in this file import movie routes and then add app.use /api movies routes save this file now in order to test this api we need to have movies in our database so i have created this config folder inside that created movies.json file. inside this file i have array of movie details we will push this array of movies to our database you can find this json file from github repo i will add it in description now lets write this function in movies.js file first import movies.json file and save it in a variable then create async function name insert movies with try catch block in it. In try block add await movie.insertMany and pass movies array save the result and return if error occurred we return error then call this function console.log docs and errors save this file now now open command prompt by starting our project insert movies function will execute so our movies will be added to database to start our project enter npm start command ok connected to database and here we go our movie is also added dont stop our project lets go to vs code and comment out insert movies function because we dont need this anymore after making changes save this file now its time to test our api open postman okay i am in postman i have already added this api lets call by clicking on send button as you can see we have got our response total documents are 14 and its page 1 lets change it to page 2 now we are in page 2 lets set limit to 6 instead of default 5 and it is also working fine now i want movies with genre drama on page 2. lets see what we get in results okay it is also working lets go to page one now lets sort movies by year default is ascending lets set desc to get in descending order if you want movies with multiple genres add , and then add genre last one more left search i will search godfather movie by just adding god because im lazy this api is working fine now lets wrap things up in next video were gonna use this api in react project to learn how to handle pagination sort search and filter on frontend. subscribe to my channel to dont miss next video or for exciting future videos i hope you have learned something new today by watching this video so bye you
CyberWolves: Implement Search, Sort, Filter and Pagination Rest API With Node JS | Express | MongoDB - Web Development