skip to Main Content

I have a MERN stack application and I have written the search query and pagination in Nodejs, I implemented the pagination part in Reactjs and wanted to implement the search query too. It is working but without pagination. I was like what if the search result is over 20 results and I simply want to make it two pages. I could do something like 12 search results per page. Is there a way to do this? Can I add both search and pagination queries in a single URL? Here is my nodejs code:

const DEFAULT_PAGE_NUMBER = 1
const DEFAULT_PAGE_LIMIT = 12;


const getPagination =(query) =>{
const page = Math.abs(query.page) || DEFAULT_PAGE_NUMBER;
const limit = Math.abs(query.limit) || DEFAULT_PAGE_LIMIT;

const skip = (page -1) * limit


return {
    skip,
    limit
};

};


const getAllPosts = async (req, res) =>{
      const {skip, limit} = getPagination(req.query);
       const {searches} = req.query;

  if(searches){
       posts = await Post.find({title: {$regex: searches.toString(), "$options": "i"}}).populate('username', 'username').sort({createdAt:-1})
       .skip(skip)
       .limit(limit)  
           
   }
 }

Now, in Reactjs, I did something like this for pagination query:

useEffect(()=>{
 try{
    const response = await axios.get(`/posts/?page=${path}`);
 }catch(err){
 
  }


}, [path]);

This works for pagination and posts are displayed 12 per page.

Now, in Reactjs, I did something like this for search query:

useEffect(()=>{
 try{
    const response = await axios.get(`/posts/?searches=${path}`);
 }catch(err){
 
  }


}, [path])

Now, this works. It fetch posts based on the search term the user input. The problem is that the result could be way more than I wanted in a page. Is there a way I could integrate the pagination query that I wrote also into this so that when a search result is more than 12, the other posts would be called on the next page?

2

Answers


  1. I sorted this out by passing the search parameter in the body and the pagination on the query. This sorted out my issue. See sample codes

    const { skip, limit } = getPagination(req.query); // pagination
    const search = req.body.search; // search 
    
      if (search) {
            
          posts = await Post.find({ title: { $regex: search.toString(), "$options": "i" } })
              .populate('username', 'username').sort({ createdAt: -1 })
              .skip(skip)
              .limit(limit)
        
      } else {
        /* fetch the entire posts if there is no search parameter. */
      }
    
    Login or Signup to reply.
  2. datatables plugin provides really good pagination out of the box

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search