189
rated 0 times
[
193]
[
4]
/ answers: 1 / hits: 7465
/ 2 Years ago, sun, july 24, 2022, 12:00:00
My productController.js
const Product = require('../models/product');
const ErrorHandler = require('../utils/errorHandler');
const catchAsyncError = require('../middlewares/catchAsyncErrors');
const APIFeatures = require('../utils/apiFeatures');
// Get all products => /api/v1/products
exports.getProducts = catchAsyncError(async (req, res, next) => {
const resPerPage = 4;
const productCount = await Product.countDocuments();
const apiFeatures = new APIFeatures(Product.find(), req.query)
.search()
.filter()
.pagination(resPerPage)
const products = await apiFeatures.query;
res.status(200).json({
success: true,
count: products.length,
message: 'All products fetched from the database successfully.',
productCount,
products
})
}
)
My APIFeatures.js
const { remove } = require("../models/product");
class APIFeatures {
constructor(query, queryStr) {
this.query = query;
this.queryStr = queryStr;
}
search() {
const keyword = this.queryStr.keyword ? {
name: {
$regex: this.queryStr.keyword,
$options: 'i' // Case insensitive option
}
} : {}
this.query = this.query.find({ ...keyword })
return this;
}
filter() {
const queryCopy = { ...this.queryStr };
// Remove the fields from the query string
const removeFields = ['keyword', 'limit', 'page']
removeFields.forEach(el => delete queryCopy[el]);
// Advanced filtering
let queryStr = JSON.stringify(queryCopy);
queryStr = queryStr.replace(/b(gt|gte|lt|lte|in)b/g, match => `$${match}`);
this.query = this.query.find(JSON.parse(queryStr));
return this;
}
pagination(resPerPage) {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resPerPage * (currentPage - 1);
this.query = this.query.limit(resPerPage).skip(skip)
}
}
module.exports = APIFeatures;
There's a problem with getting all products. Getting single product works fine so I removed that part of the code. The problem is with the query.
I have 2 sample product in my database and it was working fine. I didn't make changes this file but I can't fetch all products using postman.
const products = await apiFeatures.query;
More From » node.js