this is my ads get all controller function: exports.getAll = catchAsync(async (req, res,…
- User
this is my ads get all controller function:
exports.getAll = catchAsync(async (req, res, next) => { const filter = {}; // Assuming filter is defined somewhere or passed in req.query const features = new APIFeatures(Ad.find(filter), req.query) .filter() .sort() .limitFields() .paginate(); const doc = await features.query;
if (!doc) { return next(new AppError("No Ad Found!", 404)); }
res.status(200).json({ status: "success", data: { data: doc, }, }); });
and this is my apiFeatures: class APIFeatures { constructor(query, queryString) { this.query = query; this.queryString = queryString; }
filter() { const queryObj = { ...this.queryString }; const excludedFields = ["page", "sort", "limit", "fields"]; excludedFields.forEach((el) => delete queryObj[el]);
codelet queryStr = JSON.stringify(queryObj); queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, (match) => `$${match}`); this.query = this.query.find(JSON.parse(queryStr)); return this;}
limitFields() { if (this.queryString.fields) { const fields = this.queryString.fields.split(",").join(" "); this.query = this.query.select(fields); } else { this.query = this.query.select("-__v"); }
codereturn this;}
paginate() { const page = this.queryString.page * 1 || 1; const limit = this.queryString.limit * 1 || 100; const skip = (page - 1) * limit;
codethis.query = this.query.skip(skip).limit(limit); return this;}
sort() { if (this.queryString.sort) { const sortFields = this.queryString.sort.split(","); const sortBy = sortFields .map((field) => { if (field.startsWith("asc")) { return field.slice(3); // Remove 'asc' prefix and sort in ascending order } else if (field.startsWith("desc")) { return
-${field.slice(4)}; // Remove 'desc' prefix and sort in descending order } else if (field === "newest") { return "-createdAt"; // Sort by newest } else { return field; // Default case, in case of no 'asc' or 'desc' } }) .join(" "); this.query = this.query.sort(sortBy); } else { this.query = this.query.sort("-createdAt"); }codereturn this;} }
module.exports = APIFeatures;
now I need this option to be able to perform a get query to get all ads with north direction or in a specific district or in other word filtering a cretin value on a cretin field how to do it?
- Assistant