Reputation: 1310
All,
Question, I've got a query, that filters posts based on several criteria and then returns those posts. I then set a limit, skip (for pagination) and return them to the user.
What I'm trying to do now is implement pagination, what I need is to find count of total documents that match above query.
Basically, if I have, 100+ documents lets say in db that match query, but only returning 25. I need total count that match query.
Here is my query, I read about aggregate but not sure 100% how to implement it, or find a better solution to return total count of documents that match my query:
let regex = new RegExp(value.searchQuery, "i");
const query = Post.find();
if (value.searchQuery && value.city && value.category) {
query.where({
$and: [
{
$or: [{ title: regex }, { description: regex }]
}
],
city: value.city,
category: value.category
});
} else if (value.searchQuery && value.city && !value.category) {
query.where({
$and: [
{
$or: [{ title: regex }, { description: regex }]
}
],
city: value.city
});
} else if (value.searchQuery && value.category && !value.city) {
query.where({
$and: [
{
$or: [{ title: regex }, { description: regex }]
}
],
category: value.category
});
} else if (value.searchQuery && !value.city && !value.category) {
query.where({
$and: [
{
$or: [{ title: regex }, { description: regex }]
}
]
});
} else if (!value.searchQuery && value.city && value.category) {
query.where({ city: value.city, category: value.category });
} else if (!value.searchQuery && value.city && !value.category) {
query.where({ city: value.city });
} else if (!value.searchQuery && value.category && !value.city) {
query.where({ category: value.category });
}
if (value.sort.createdAt) {
query.setOptions({ createdAt: value.sort.createdAt });
} else if (value.sort.deadline) {
query.setOptions({ deadline: value.sort.deadline });
}
query
.setOptions({
limit: limitPerPage,
skip: skipAmount,
sort: !value.sort.createdAt
? { deadline: value.sort.deadline }
: { createdAt: value.sort.createdAt }
})
.exec();
Upvotes: 1
Views: 6945
Reputation: 154
You will have to perform second operation to get the count using query.countDocuments()
Upvotes: 3