Home > Back-end >  How can get all data after query search data using mongoose-paginate?
How can get all data after query search data using mongoose-paginate?

Time:11-03

enter image description hereMy query string search is okay but only problem is when remove and display all data...:-(

My code is here

  router.get('/allStudents', async (req,res) => {

  const limit = parseInt(req.query.limit, 4) || 4;
  const page = parseInt(req.query.page, 10) || 1;

  const PAGE_SIZE = 10;
  const skip = (page - 1) * PAGE_SIZE;

  try {

       const stdID = await Student.paginate({stdID: req.query.stdID}, {limit, page, 
        skip}) //OK it works!!! but as its remove it wont display the whole data (data:[])

       return res.status(200).json({
         success: true,
         data: stdID
       })
  
  } catch (err) {
      console.log(err);
  }

  });

CodePudding user response:

add condition for search

 router.get('/allStudents', async (req,res) => {

  const limit = parseInt(req.query.limit, 4) || 4;
  const page = parseInt(req.query.page, 10) || 1;

  const PAGE_SIZE = 10;
  const skip = (page - 1) * PAGE_SIZE;

  try {
       if (req.query.stdID.length >= 0){ // or (req.query.stdID!==null || req.query.stdID!== undefined) 
       const stdID = await Student.paginate({stdID: req.query.stdID}, {limit, page, 
        skip}) //OK it works!!! but as its remove it wont display the whole data (data:[])
    }
      else {
const stdID = await Student.paginate({}, {limit, page, 
        skip})
       return res.status(200).json({
         success: true,
         data: stdID
       })}
       
  
  } catch (err) {
      console.log(err);
  }

  });

CodePudding user response:

What @mohammad Naimi answered is right, but to explain it in layman terms -->

When you pass data you get stdID in req.query so your mongo query works just fine as you said, but when you are removing all data ,it makes the req.query.stdID a null field which causes the error as there is no req.query.

you can pass it as shown by Mohammad above or also using Ternary operators.

let mongoQuery = req.query.stdID ? {stdID: req.query.stdID} : {} ;

and pass the mongoQuery in your paginate function.

  • Related