I’m applying **filtering **on my data using three different filters mentioned in my code.
this is my code
/* Initialize pipeline */
const pipeline = [];
/* All reviews of Auth Host */
pipeline.push({
$match: { host_id: new ObjectId(host_id) },
});
/* High rated on top */
if (filter && filter == "Highest Rated") {
pipeline.push({
$sort: {
rating: -1,
_id: -1,
},
});
} else if (filter && filter == "Newest") {
/* Newest on top */
pipeline.push({
$sort: {
_id: -1,
},
});
} else if (filter && filter == "Oldest") {
pipeline.push({
$sort: {
_id: 1,
},
});
}
/* Pagination */
if (last_rec_id) {
let query;
if (filter !== "Highest Rated") {
query = filter === "Oldest" || !filter ? { $gt: new ObjectId(last_rec_id) } : { $lt: new ObjectId(last_rec_id) };
pipeline.push({
$match: {
_id: query,
},
});
} else {
query = {
$or: [
{ rating: { $lte: 5 } },
{
rating: 5,
_id: { $lt: new ObjectId(last_rec_id) }, // Secondary sorting by _id
},
],
};
pipeline.push({
$match: query,
});
}
}
All filters are working well with pagination but the pagination using **last_rec_id **is not applying on filter="Highest Rated", i’m getting records well but when i apply pagination it donot give accurate results,
>Solution :
Instead of Last Record Id I would prefer to paginate using Page Number.
/* Initialize pipeline */
const pipeline = [];
/* All reviews of Auth Host */
pipeline.push({
$match: { host_id: new ObjectId(host_id) },
});
/* High rated on top */
if (filter && filter == "Highest Rated") {
pipeline.push({
$sort: {
rating: -1,
_id: -1,
},
});
} else if (filter && filter == "Newest") {
/* Newest on top */
pipeline.push({
$sort: {
_id: -1,
},
});
} else if (filter && filter == "Oldest") {
pipeline.push({
$sort: {
_id: 1,
},
});
}
/* Pagination Logic */
if (page) {
const pageSize = 10; // Change this to your desired page size
const skipAmount = (page - 1) * pageSize;
pipeline.push({
$skip: skipAmount,
});
}