'nodejs how to add result of sub request to my main request
I am trying to retrieve my blog posts and categories (tag) via my database.
I make a first query to retrieve the list of my blog posts and then I create a new query to retrieve the tags of my posts (as they are on a different table)
I have a table : blog, tag, blog_tag ( which makes the join of the two previous tables).
My question is how can I add my tag object in my Results.tag variable?
Thank's in advance
app.get("/api/get", (req, res) =>{
bdd.query("SELECT * FROM blog limit 2", (err, result) => {
if(err){
console.log(err)
throw err;
}else{
result.map((element, key) => {
result[key].tag = []
bdd.query(`SELECT tag.id, tag.name AS 'categorie', blog_tag.blog_id AS 'postId' FROM blog_tag JOIN tag ON blog_tag.tag_id = tag.id WHERE blog_tag.blog_id = ?`, element.id, (err, result_tag) => {
if(err){
console.log(err)
throw err;
}
// I'm trying here adding my tag to each blog articles
result_tag.map((tag) => {
if(tag.postId === element.id){
result[key].tag = [...result[key].tag, tag]
}
})
})
})
console.log(result)
}
res.send(result)
})
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
