A
A
askold20132018-01-23 16:10:36
MongoDB
askold2013, 2018-01-23 16:10:36

How to limit the number of documents in a mongoose fetch?

Hello! I'm trying to make a database fetch script using mongoose. What I want to do is have a collection that contains posts that have different categories. I need to get posts from each category, and 5 posts each. limit() is not suitable, because the code will become much more complicated (you need to find it in the current category, wait for the answer, the next one - can it be simpler?)
I did this:

const Posts = mongoose.model('post');
    const Categories = mongoose.model('category');
    // create request obj
    const findPostsRequest = (categories) => {
        if (!categories.length) return {};
        let request = { $or: [] };
        categories.map(category => {
            request.$or.push({ 'categories.link': category.link });
        });
        console.log(request);
        return request;
    };
    // find all categories
    Categories.find()
        .then(categories => {
            // find 5 posts in every category from categories
            Posts.find(findPostsRequest(categories))
                .then(posts => {
                    res.status(201).json(posts);
                })
                .catch(err => {
                    res.send({
                        message: `Ой ошибка:  + ${err.message}`
                    });
                });
        })
        .catch(err => {
            res.status(400).json({
                message: `При получени записей произошла ошибка:  + ${err.message}`
            });
        });

That is, we get all categories, and then add category conditions in one query with an array OR. I need to shove $slice somewhere, but I still don't understand where. You need to get 5 posts from each category. How to do it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question