Categories
Development HTTP MongoDB

NodeJS mongodb query ERR_HTTP_HEADERS_SENT

I have a nodejs mongoose backend api with express, whose objective is, for each website page, it returns a certain number of objects sorted by ID.

My question is relatively simple but it’s easier to exemplify. Let’s say the user has choosen to display 20 objects per page and it’s on page 0. The api will return the first 20 objects (0 to 19) from the mongoDB collection. Page 2 with 20 will return the next 20 objects ordered by ID ( objects 20 to 39).

Right now the code looks like this:

var page = (req.query.page) ? parseInt(req.query.page) : 0;
var qtd = (req.query.qtt) ? parseInt(req.query.qtt) : 20;
var min_value = page * qtd;
var max_value =( page + 1 ) * qtd - 1;

Order.find({}, {skip:min_value,limit:max_value}, function(err,orders) {
    if (err) {
        res.json({
            status: "error",
            message: err,
        });
    }
    res.json({
        status: "success",
        message: "Orders retrieved successfully",
        data: orders
    });
});

};

My question is, why do I keep getting “Cannot set headers after they are sent to the client” and how would I sort the query alongside limit and skip.

Leave a Reply

Your email address will not be published. Required fields are marked *