Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda