I'm trying to get the lastest records in a database. I have a field with their category. I'm trying to get 20 records, 5 of the latest post in each category. What I mean is that it should return 20 latest records but 5 of each category since the latest 20 does not necessarily mean a balanced 5 of each category. Basically what I have below, but I feel there's a better way and wasn't able to see it from reading the Sequelize docs. Thanks guys, I really appreciate it! Pardon the pseudocode. I have 4 categories. and im actually also sorting by createdAt timestamp field with limits and attributes and other checks/ error handling that I have not included for the sake of readability.
Posts.findAll({ where: { category: "Tech"}})
.then(techPosts => {
Posts.findAll({where:{category: "Science"},})
.then(sciencePosts => {
//actually 2 more nested findAlls before sending
const posts = [...techPosts, ...sciencePosts]
res.status(200).json(posts).end();
})
})
I would suggest fetching 5 different categories at the same time using "Promise.all". The code would look like this:
const fetchTechPosts = () => {
return Posts.findAll({ where: { category: "Tech"}})
}
const fetchSciencePosts = () => {
return Posts.findAll({ where: { category: "Science"}})
}
const promises = Promise.all([fetchTech, fetchScience])
promises.then(posts => {
res.status(200).json(posts).end()
})