Home > other >  Better way to avoid applying repetitive mongoose method
Better way to avoid applying repetitive mongoose method

Time:07-01

I am using the below code in order to first filter documents in mongoose based on some filter. Then I am required to count the documents filtered.
Then, as can be seen in the code, since I have to skip some documents to send to the client, I have to again apply the find() method in order to filter the documents and then apply the skip() and limit() method.

const count = await myModel.find(filterObj).countDocuments();
const docs = await myModel
  .find(filterObj)
  .skip((page - 1) * pageSize)
  .limit(pageSize);

Is there any better way so that I can avoid applying the find() method twice since this seems to be costly if we have a large no. of documents?

CodePudding user response:

regarding performance of the action taken in the code snippet there's no further room for optimization find, limit and skip is sufficient enough (Make sure you have indexes to further optimize query times)

NodeJS wise you can use promise.all to run queries simultaneously

 const count = ()=>await myModel.find(filterObj).countDocuments();
 const docs = ()=>await myModel
 .find(filterObj)
 .skip((page - 1) * pageSize)
 .limit(pageSize);
 const [docsResult,CountResult] = await Promise.all([docs(),count()])
  • Related