Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js mongoose populate limit

I have two schema say city and blogs. I want to create a blog page with pagination. So I am populating blogs with reference to city name. Say if I dont have a blog for a city then it should not be returned. Here is my query to get the blogs.

City.find().skip(req.params.pageIndex*2).limit(2).sort('-created').populate('articles').exec(function(err, cities) {

res.jsonp(cities)

}

If I use the above query. I get the cities with no blogs as well. So it results in an empty row in the view. I don't want that to happen. How to limit the populated field and not return the city without blogs. Any suggestions?

like image 277
prdtuty Avatar asked Aug 25 '15 14:08

prdtuty


2 Answers

Instead of using

{options:{limit:2}}

Use like

{perDocumentLimit:2}

Its works for me

like image 116
Praveen AK Avatar answered Oct 27 '22 10:10

Praveen AK


City.find({}).populate({
    path:'Articles',
    options: {
        limit: 2,
        sort: { created: -1},
        skip: req.params.pageIndex*2

    }
}).exec(function (err, cities) {
    if (err) return handleError(res, err);
    return res.status(200).json(cities);
});
like image 34
camilo posada Avatar answered Oct 27 '22 10:10

camilo posada