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

108
Views
Sequelize.js get orders divided by the status

I have a Node.JS project and am using sequelize as the ORM. I would like to run a query where I get all of my orders grouped by the status. So I would get for example an object with 5 keys (given that I have 5 different statuses). And in each key there would be an array with all orders that have that status.

Example of object:

{

"Done": [{id:1, item: "bag"}, {id:2, item: "purse"}],
"Processing":  [{id:3, item: "bag"}, {id:4, item: "purse"}],
"Pending":  [{id:5, item: "bag"}, {id:6, item: "purse"}]

}

Is this possible in any way or I need to get all possible statuses and just run the same number of queries each time changing the where clause?

Thanks

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

.findAll() gives you back a result set consisting of an array of model instances. I guess in your case it will be an array of Orders. It's flattened, not hierarchical.

That will look something like this.

[
  {status: "Done",       id:1, item: "bag"},
  {status: "Done",       id:2, item: "purse"},
  {status: "Processing", id:3, item: "bag"},
  {status: "Processing", id:4, item: "purse"},
  {status: "Pending",    id:5, item: "bag"}, 
  {status: "Pending",    id:6, item: "purse"}
]

You can then turn that flattened result set into the hierarchical one you want. Something like this, not debugged, should do the job.

const byStatus = {}
for (const row of resultSet) {
  /* first time we've seen this status value? if so create an array for it. */
  if (!byStatus[row.status]) byStatus[row.status] = []
  /* put the present row into the appropriate array */
  byStatus[row.status].push( {id: row.id, item: row.item })
}

That way you can run just one .findAll() query. That's a good idea because it's more efficient than running multiple ones.

about 4 years ago · Juan Pablo Isaza Report

0

You need to use a "native" query with a GROUP BY clause or you fetch the data normally and do the gruoping in JS/TS using lodash's groupBy.

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!