Nicholas Harris
Nicholas Harris

Reputation: 103

Get data from MySQL database and add to list (NodeJS)

So using a list of ids, I'm trying to get data for each element in the database and add that element to a list. At the end, I'm displaying it on an HTML page. How would I do that? Right now, since it executes the queries async, the list will be empty after running the code to execute the query and add the result to a list.

Upvotes: 0

Views: 1515

Answers (1)

Patrick Motard
Patrick Motard

Reputation: 2660

Lets assume you have a table called teams that contains a row for each team, with columns like id, games, total_points, wins, and losses.

Lets assume you have an array of team id. You want to query the database for those records, then do some things with them before returning them to the front end as json.

This is how i understand your problem. If this isn't the case, please clarify in a comment on this answer.

Possible solution: Do it all in one query. I'm going to use my favorite mysql library, knexjs.

var columns = ['id', 'games', 'total_points', 'wins', 'loses'];

function getTeams(ids){
  return knex.select(columns).where('id', 'in', ids)
    .then((teams) => {
      //do whatever with array of teams
      return teams;
    }
}

It's pretty much as simple as that.

Upvotes: 1

Related Questions