Home > Software engineering >  parametrizing pagination for a query
parametrizing pagination for a query

Time:06-11

I've got a complex query like this:

VERSION1

export async function mPass(){
   return await MyModel.aggregate()
           .addField({$match: {//condition}})
           .lookup(//lookup query)
           .addField({$cond: {//condition}})
           .addField(//condition2)  #<---------PAGINATE DATA HERE
           .addField({$match: {//condition}})
}  

now, for the same query, I'm required to paginate the results , but, I am to paginate data after condition2 above

so, the above function would become something like this:

VERSION2

export async function mPass(pageNumber, pageSize){
   return await MyModel.aggregate()
           .addField({$match: {//condition}})
           .lookup(//lookup query)
           .addField({$cond: {//condition}})
           .addField(//condition2)  # <---------PAGINATE DATA HERE
           .skip((pageNumber-1)*pageSize)
           .limit(pageSize)
           .addField({$match: {//condition}})
}  

the problem is, I've already used the function multiple places which don't require pagination. So, I was thinking there was something like this:

.skip(-1).limit(-1)   

which would not do any skipping or limiting, but, turned to the docs and it says they both take positive values only.

So, how would I approach to parametrize the function to optionally include pagination in the query at the specified place?

CodePudding user response:

Use if statement:

export async function mPass(pageNumber = null, pageSize = null){
   let ag = MyModel.aggregate()
           .addField({$match: {//condition}})
           .lookup(//lookup query)
           .addField({$cond: {//condition}})
           .addField(//condition2)  # <---------PAGINATE DATA HERE
   if (pageSize) {
       ag.skip((pageNumber-1)*pageSize)
           .limit(pageSize)
   }
   return ag.addField({$match: {//condition}})
}

As a side note, $match after pagination is a questionable practice. You may end up with a page with less than pageSize documents, or even without documents at all.

  • Related