1

I'm building an app in Express and using Postgres for my database, Sequelize for ORM.

In my database each Post can have one of the 5 types, 1, 2, 3, 4, 5.

I want to show the amount of all the posts by type.

router.route('/post).get(async (req, res) => {
  const postOne = await Post.findAll({
    where: { 
      state: 1
    }
  });
  const postTwo = await Post.findAll({
    where: { 
      state: 2
    }
});
res.send({ postOne: postOne.length, postTwo: postTwo.length });

I can write like this for all of the 5 types, but I was wondering if there was any shorter way to do it so that I don't have to write the same code 5 times.

Thanks!

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Tom Bom
  • 1,589
  • 4
  • 15
  • 38
  • which framework do you use? what DB do you use? – skyboyer Apr 12 '18 at 08:56
  • I'm using Node and Postgres – Tom Bom Apr 12 '18 at 08:58
  • 1
    are you sure you don't use ExpressJs or something like that? I believe NodeJS [does not have](https://nodejs.org/api/) ORM included. Most ORMs provide aggregation feature that would help you to get all the counts at one single query. – skyboyer Apr 12 '18 at 09:05
  • thanks @skyboyer I clarified my question – Tom Bom Apr 12 '18 at 09:11
  • Now after clarification it seems next link is exactly what you need: https://stackoverflow.com/questions/22627258/how-does-group-by-works-in-sequelize – skyboyer Apr 12 '18 at 13:29

2 Answers2

0
const getPostWithType = (type) => Post.findAll({
  where: { 
    state: type
  }
});

Now you can await getPostWithType(1) instead. Or even better:

const postTypes = [1,2,3,4,5];
const allPosts = await Promise.all(postTypes.map(getPostWithType));

// allPosts is now an array with the results. You can map it again to get the lengths
const allPostLengths = allPosts.map(p => p.length);
0

what about using an array? Like below...

let promiseArray = [];

for (let i = 1; i <= 5; i++) {
  let promise = Post.findAll({
    where: { 
      state: i
    }
  });

  promiseArray.push(promise);
}

Promise.all(promiseArray).then(function(response) {
  //Do whatever...
});
Luiz Duarte
  • 131
  • 2
  • 3