Can you do something like this in one query?
-- this gets you foods #133, #139, and #140
SELECT field_1, field_2, field_5
FROM foods
WHERE food_id IN (133, 139, 140);
Here’s an example in Node using the monsters code from the tutorial:
function getAllMonsters(limit = 100) {
return new Promise((resolve, reject) => {
// Use question marks for each placeholder.
const sql = `SELECT * FROM monsters WHERE id IN (?) LIMIT ?`;
// The array here has one item to fill each question mark. So
// `[1, 3]` fills the first question mark and `limit` fills the
// second question mark.
pool.query(sql, [[1, 3], limit], function (err, results, fields) {
if (err) {
return reject(err);
}
return resolve(results);
});
});
}
To pass in the food IDs as an array, you could probably do something like this:
// Pass the `foodIds` in to the function here. You can remove `limit` if
// you don't need it.
function getSomeFoods(foodIds, limit = 100) {
return new Promise((resolve, reject) => {
// Use question marks for each placeholder.
const sql = `SELECT * FROM foods WHERE id IN (?) LIMIT ?`;
// Now, `foodIds` is an array that populates the first question
// mark.
pool.query(sql, [foodIds, limit], function (err, results, fields) {
if (err) {
return reject(err);
}
return resolve(results);
});
});
}
Edit: here is an example of passing in multiple food IDs by URL. Your code will probably be different, but this shows the general idea.
function getSomeFoods(ids, limit = 100) {
return new Promise((resolve, reject) => {
const sql = `SELECT * FROM foods WHERE food_id IN (?) LIMIT ?`;
pool.query(sql, [ids, limit], function (err, results, fields) {
if (err) {
return reject(err);
}
return resolve(results);
});
});
}
// The URL would be something like this, with comma-separated IDs:
// http://localhost:3333/api/foods/1,2,10,25
app.get("/api/foods/:ids", (req, res) => {
// Extract the food IDs from the params into an array
const ids = req.params.ids.split(",");
// Pass the IDs into the function
db.getSomeFoods(ids)
.then(data => res.json(data))
.catch(err => res.status(500).json(err));
});
Someone else here might have a better idea. 