Answer the question
In order to leave comments, you need to log in
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}`
});
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question