john-smilga / node-express-course

3.56k stars 3.71k forks source link

04-STORE-API: page functionality is not working #53

Open AkmDgreat opened 1 year ago

AkmDgreat commented 1 year ago

In post-man, when I set page =1, I get this response:

image

Now, when I set page = 2, I get the same response:

image

I am supposed to get different responses for different values of page, but I am getting the same response. Where did I go wrong?

This is controllers/product.js :

const Product = require("../models/product")
const productsList = require("../products.json")

const getAllProductsStatic = async (req, res) => {
    const search = "a"
    const products = await Product
                            .find({ 
                                featured: false, 
                                name: { $regex: search, $options: "i" } //name: "vase table"
                            })
                            .sort("name -price")
                            .select("name price")
                            .limit(5)
                            .skip(2)
    res.status(200).json({ msg: products, numOfProducts: products.length })
}

const getAllProducts = async (req, res) => {
    console.log(req.query) 

    const { featured, company, name, sort, fields } = req.query
    const queryObject = {}

    if (featured) {
        queryObject.featured = featured === "true" ? true : false
    }

    if (company) {
        if (company == "ikea" || company == "liddy" || company == "marcos" || company == "caressa") {
            queryObject.company = company
        }
        else {
            return res.status(404).json({ msg: "this company doesn't exist")
        }
    }

    if (name) {
        queryObject.name = {
            $regex: name,
            $options: "i"
        }
    }

    let result = Product.find(queryObject)

    if (sort) {
        const sortList = sort.split(",").join(' ') //console.log(sortList) 
        result = result.sort(sortList)
    }
    else {
        result = result.sort("createdAt") 
    }

    // FIELDS
    if (fields) {
        const fieldsList = fields.split(",").join(" ")
        result = result.select(fieldsList)
    }

    const page = Number(req.query.page) || 1  
    const limit = Number(req.query.limit) || 10
    const skip = (page -1) * limit 
    result = result.skip(skip).limit(limit) 

    const products = await result

    res.status(200).json({ msg: products, numOfProducts: products.length })
}

module.exports = { getAllProducts, getAllProductsStatic }
Harsh-2909 commented 1 year ago

From what i can see from your postman, it seems as if there is a space between page and =2. Try to add the query params in your URL manually and then try again.