Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
Specifying what records are returned from database depending on certain field with Sequelize and MySQL

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();
     })
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!