0

I have this code

async findAll(query: SharedPreferences, req): Promise<IVehicle[]> {
const vehicles = this.vehicleModel
  .find({
    ...req.searchObj,
    ...req.dateQr,
  })
  .sort({ [query.sort]: query.orderBy === "desc" ? -1 : 1 })
  .skip(req.skip)
  .populate(["owner", "branch"]);

const total = vehicles;

vehicles.limit(+query.limit);

const response: any = {
  result: await vehicles,
  // count: total.countDocuments(), // this doesnt work here since vehicles already been awaited
  limit: +query.limit,
  page: +query.page,
};

return response;

}

what I'm trying to do is to get the total count of the vehicle documents without the (limit) query and also the vehicles documents (the array result of find()) with one query.

I need to separate the limit() so it doesn't count the vehicles while they are limited in order to get the actual total, but when you await the vehicles you cant access the .countDocuments() anymore since the promise is resolved.

I copied the vehicles into a new total variable which I thought will be different, but since it addresses the same query, it's no use. is there a way to implement this without making 2 queries. thanks

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35

2 Answers2

0

You can use count operator on vehicles.

async findAll(query: SharedPreferences, req): Promise<IVehicle[]> {
const vehicles = this.vehicleModel
  .find({
    ...req.searchObj,
    ...req.dateQr,
  })
  .sort({ [query.sort]: query.orderBy === "desc" ? -1 : 1 })
  .skip(req.skip)
  .populate(["owner", "branch"]);

vehicles.limit(+query.limit);

const response: any = {
  result: await vehicles,
  count: await vehicles.count(),
  limit: +query.limit,
  page: +query.page,
};

return response;

You can check more ways here to achieve the same if the above doesn't work.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
0

So this worked for me

async findAll(query: SharedPreferences, req): Promise<IVehicle[]> {
const vehicles = this.vehicleModel
  .find({
    ...req.searchObj,
    ...req.dateQr,
  })
  .sort({ [query.sort]: query.orderBy === "desc" ? -1 : 1 })
  .skip(req.skip)
  .populate(["owner", "branch"]);

const total = await vehicles.clone().count();

vehicles.limit(+query.limit);

const response: any = {
  count: total,
  result: await vehicles,
  limit: +query.limit,
  page: +query.page,
};

return response;

}

you can use .clone() to save a copy of the query, and then get the count of that before the .limit() is executed, so this will return the vehicles, and the total count without the limit.