Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
20

The error here was pagination I simply solve that by replacing


this.query = this.query.limit(resPerPage).skip(skip);
return this;

[#54] Wednesday, June 29, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryleymarkelb

Total Points: 554
Total Questions: 106
Total Answers: 95

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
ryleymarkelb questions
Thu, Nov 18, 21, 00:00, 3 Years ago
Thu, Apr 8, 21, 00:00, 3 Years ago
Fri, Aug 28, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
;