Multiple queries in one final custom JSON The Next CEO of Stack OverflowSafely turning a JSON string into an objectHow can I get query string values in JavaScript?How can I select an element with multiple classes in jQuery?Why does Google prepend while(1); to their JSON responses?Convert JS object to JSON stringHow can I pretty-print JSON using JavaScript?Parse JSON in JavaScript?How to retrieve POST query parameters?How to parse JSON using Node.js?How to get GET (query string) variables in Express.js on Node.js?

How to edit “Name” property in GCI output?

How to get from Geneva Airport to Metabief, Doubs, France by public transport?

Unclear about dynamic binding

Calculator final project in Python

Proper way to express "He disappeared them"

Reference request: Grassmannian and Plucker coordinates in type B, C, D

Rotate a column

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Where do students learn to solve polynomial equations these days?

Why do remote US companies require working in the US?

Poetry, calligrams and TikZ/PStricks challenge

Can we say or write : "No, it'sn't"?

What steps are necessary to read a Modern SSD in Medieval Europe?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Is it convenient to ask the journal's editor for two additional days to complete a review?

What is meant by "large scale tonal organization?"

Method for adding error messages to a dictionary given a key

Why didn't Khan get resurrected in the Genesis Explosion?

Why is information "lost" when it got into a black hole?

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Why, when going from special to general relativity, do we just replace partial derivatives with covariant derivatives?

A small doubt about the dominated convergence theorem

Find non-case sensitive string in a mixed list of elements?

Is a distribution that is normal, but highly skewed considered Gaussian?



Multiple queries in one final custom JSON



The Next CEO of Stack OverflowSafely turning a JSON string into an objectHow can I get query string values in JavaScript?How can I select an element with multiple classes in jQuery?Why does Google prepend while(1); to their JSON responses?Convert JS object to JSON stringHow can I pretty-print JSON using JavaScript?Parse JSON in JavaScript?How to retrieve POST query parameters?How to parse JSON using Node.js?How to get GET (query string) variables in Express.js on Node.js?










0















I'm trying to create an api route using Node and Express and I must say I don't have much experience with it. Right know I have the following code:



app.get('/api/place/:id', (req, res) => 
var id = req.params.id;
var message_error = '"status": "failed", "message": "Unable to fetch data"';

db.query("SELECT `id`, `user`, `lat`, `lon`, `elevation`, `rating`, `rating_count`, `country`, `continent`, `locality` FROM `t_points` WHERE id = ?", [id], (err, res1) =>
if(err)
res.json(message_error);
else
//Store the user id from the points table and use it to fetch user datas
var userId = res1[0].user;
if(userId != null)
db.query("SELECT `id`, `name` FROM `t_users` WHERE `id` = ?", [userId], (err, res2) =>
if(err)
res.json(message_error);
else
//Final json structure
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count,
user:
id: res2[0].id,
name: res2[0].name

);

);
else
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count
);


);
);


I'm hard-coding the json structure so if the userId in my table is null I don't print the user object in the json, otherwise I print it. But that's not a good idea, as I will also add more queries in the same route. Is there a simple way to create just one json at the end of all the queries and if some values are null not showing it?



Also, would it be better to use async and await functions to do it, instead of this way?



Thanks!










share|improve this question
























  • Why wouldn't you just use a join?

    – Strawberry
    Mar 8 at 16:35











  • I was thinking of using that actually, that might get things simpler. But for the json I don't know if it's helpful? Also, I have 5 more queries in the route

    – astronomy-domine
    Mar 8 at 16:39












  • Well, it means you're just manipulating an array, based on the result of a single query, rather than mashing together the results of 1+n queries.

    – Strawberry
    Mar 8 at 16:41











  • Thanks, I will use that, but if the returned value is null I will have the "user" object anyway

    – astronomy-domine
    Mar 8 at 16:48











  • I don't understand why that makes a difference.

    – Strawberry
    Mar 8 at 16:52















0















I'm trying to create an api route using Node and Express and I must say I don't have much experience with it. Right know I have the following code:



app.get('/api/place/:id', (req, res) => 
var id = req.params.id;
var message_error = '"status": "failed", "message": "Unable to fetch data"';

db.query("SELECT `id`, `user`, `lat`, `lon`, `elevation`, `rating`, `rating_count`, `country`, `continent`, `locality` FROM `t_points` WHERE id = ?", [id], (err, res1) =>
if(err)
res.json(message_error);
else
//Store the user id from the points table and use it to fetch user datas
var userId = res1[0].user;
if(userId != null)
db.query("SELECT `id`, `name` FROM `t_users` WHERE `id` = ?", [userId], (err, res2) =>
if(err)
res.json(message_error);
else
//Final json structure
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count,
user:
id: res2[0].id,
name: res2[0].name

);

);
else
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count
);


);
);


I'm hard-coding the json structure so if the userId in my table is null I don't print the user object in the json, otherwise I print it. But that's not a good idea, as I will also add more queries in the same route. Is there a simple way to create just one json at the end of all the queries and if some values are null not showing it?



Also, would it be better to use async and await functions to do it, instead of this way?



Thanks!










share|improve this question
























  • Why wouldn't you just use a join?

    – Strawberry
    Mar 8 at 16:35











  • I was thinking of using that actually, that might get things simpler. But for the json I don't know if it's helpful? Also, I have 5 more queries in the route

    – astronomy-domine
    Mar 8 at 16:39












  • Well, it means you're just manipulating an array, based on the result of a single query, rather than mashing together the results of 1+n queries.

    – Strawberry
    Mar 8 at 16:41











  • Thanks, I will use that, but if the returned value is null I will have the "user" object anyway

    – astronomy-domine
    Mar 8 at 16:48











  • I don't understand why that makes a difference.

    – Strawberry
    Mar 8 at 16:52













0












0








0








I'm trying to create an api route using Node and Express and I must say I don't have much experience with it. Right know I have the following code:



app.get('/api/place/:id', (req, res) => 
var id = req.params.id;
var message_error = '"status": "failed", "message": "Unable to fetch data"';

db.query("SELECT `id`, `user`, `lat`, `lon`, `elevation`, `rating`, `rating_count`, `country`, `continent`, `locality` FROM `t_points` WHERE id = ?", [id], (err, res1) =>
if(err)
res.json(message_error);
else
//Store the user id from the points table and use it to fetch user datas
var userId = res1[0].user;
if(userId != null)
db.query("SELECT `id`, `name` FROM `t_users` WHERE `id` = ?", [userId], (err, res2) =>
if(err)
res.json(message_error);
else
//Final json structure
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count,
user:
id: res2[0].id,
name: res2[0].name

);

);
else
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count
);


);
);


I'm hard-coding the json structure so if the userId in my table is null I don't print the user object in the json, otherwise I print it. But that's not a good idea, as I will also add more queries in the same route. Is there a simple way to create just one json at the end of all the queries and if some values are null not showing it?



Also, would it be better to use async and await functions to do it, instead of this way?



Thanks!










share|improve this question
















I'm trying to create an api route using Node and Express and I must say I don't have much experience with it. Right know I have the following code:



app.get('/api/place/:id', (req, res) => 
var id = req.params.id;
var message_error = '"status": "failed", "message": "Unable to fetch data"';

db.query("SELECT `id`, `user`, `lat`, `lon`, `elevation`, `rating`, `rating_count`, `country`, `continent`, `locality` FROM `t_points` WHERE id = ?", [id], (err, res1) =>
if(err)
res.json(message_error);
else
//Store the user id from the points table and use it to fetch user datas
var userId = res1[0].user;
if(userId != null)
db.query("SELECT `id`, `name` FROM `t_users` WHERE `id` = ?", [userId], (err, res2) =>
if(err)
res.json(message_error);
else
//Final json structure
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count,
user:
id: res2[0].id,
name: res2[0].name

);

);
else
res.json(
id: res1[0].id,
lat: res1[0].lat,
lon: res1[0].lon,
elevation: res1[0].elevation,
rating: res1[0].rating,
rating_count: res1[0].rating_count
);


);
);


I'm hard-coding the json structure so if the userId in my table is null I don't print the user object in the json, otherwise I print it. But that's not a good idea, as I will also add more queries in the same route. Is there a simple way to create just one json at the end of all the queries and if some values are null not showing it?



Also, would it be better to use async and await functions to do it, instead of this way?



Thanks!







javascript mysql node.js express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 16:24







astronomy-domine

















asked Mar 8 at 16:22









astronomy-domineastronomy-domine

196




196












  • Why wouldn't you just use a join?

    – Strawberry
    Mar 8 at 16:35











  • I was thinking of using that actually, that might get things simpler. But for the json I don't know if it's helpful? Also, I have 5 more queries in the route

    – astronomy-domine
    Mar 8 at 16:39












  • Well, it means you're just manipulating an array, based on the result of a single query, rather than mashing together the results of 1+n queries.

    – Strawberry
    Mar 8 at 16:41











  • Thanks, I will use that, but if the returned value is null I will have the "user" object anyway

    – astronomy-domine
    Mar 8 at 16:48











  • I don't understand why that makes a difference.

    – Strawberry
    Mar 8 at 16:52

















  • Why wouldn't you just use a join?

    – Strawberry
    Mar 8 at 16:35











  • I was thinking of using that actually, that might get things simpler. But for the json I don't know if it's helpful? Also, I have 5 more queries in the route

    – astronomy-domine
    Mar 8 at 16:39












  • Well, it means you're just manipulating an array, based on the result of a single query, rather than mashing together the results of 1+n queries.

    – Strawberry
    Mar 8 at 16:41











  • Thanks, I will use that, but if the returned value is null I will have the "user" object anyway

    – astronomy-domine
    Mar 8 at 16:48











  • I don't understand why that makes a difference.

    – Strawberry
    Mar 8 at 16:52
















Why wouldn't you just use a join?

– Strawberry
Mar 8 at 16:35





Why wouldn't you just use a join?

– Strawberry
Mar 8 at 16:35













I was thinking of using that actually, that might get things simpler. But for the json I don't know if it's helpful? Also, I have 5 more queries in the route

– astronomy-domine
Mar 8 at 16:39






I was thinking of using that actually, that might get things simpler. But for the json I don't know if it's helpful? Also, I have 5 more queries in the route

– astronomy-domine
Mar 8 at 16:39














Well, it means you're just manipulating an array, based on the result of a single query, rather than mashing together the results of 1+n queries.

– Strawberry
Mar 8 at 16:41





Well, it means you're just manipulating an array, based on the result of a single query, rather than mashing together the results of 1+n queries.

– Strawberry
Mar 8 at 16:41













Thanks, I will use that, but if the returned value is null I will have the "user" object anyway

– astronomy-domine
Mar 8 at 16:48





Thanks, I will use that, but if the returned value is null I will have the "user" object anyway

– astronomy-domine
Mar 8 at 16:48













I don't understand why that makes a difference.

– Strawberry
Mar 8 at 16:52





I don't understand why that makes a difference.

– Strawberry
Mar 8 at 16:52












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55067131%2fmultiple-queries-in-one-final-custom-json%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55067131%2fmultiple-queries-in-one-final-custom-json%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived