moongose paginate doesn't sort items

11 Views Asked by At

I'm working with moongose, express, handlebars and moongose-paginate-v2, I have an issue where I want products to render by price, the problem is that for some reason sort does not work, it doesn't even throw an error, maybe I'm using it wrong? the render works properly, it just doesn't bring my collection by price

router.get('/products', async (req,res)=>{
    const {limit, page, stock, category, sort} = req.query
    try{
        const products = await productService.getProductsByPagination(limit, page, stock, category, sort)
        products.stock = stock
        products.category = category

        res.render('products',products)
    } catch(err){
        res.send(err)
    }

})

this is my function:

async getProductsByPagination(limit = 10, page = 1, stock= false, category= false){
    let filter = {}
    let sort = {}

    if(stock){
        filter = { ...filter, stock }
    }

    if(category){
        filter = { ...filter ,category }
    }

    if(category || stock){
        sort = {price: 1}
    }

    return  this.model.paginate(filter, {lean: true, limit, page, sort})
}
0

There are 0 best solutions below