Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda