Multiple mysql queries with Express Node











up vote
0
down vote

favorite












I am running an Express server and connecting to MySQL Database. I am have two tables which are referenced via the user_id. When the user provides the email address I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this? Also any best practice recommendations for any part of the code is appreciated!



Thanks



MySQL



CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT UNIQUE,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) DEFAULT NULL,
email VARCHAR(320) NOT NULL UNIQUE,
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id)
);

CREATE TABLE tracking (
tracking_id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
metric VARCHAR(100) NOT NULL,
unit VARCHAR(100) NOT NULL,
amount DOUBLE DEFAULT NULL,
date_tracked DATE,
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (tracking_id),
INDEX user_ind (user_id),
FOREIGN KEY (user_id)
REFERENCES users(user_id)
ON DELETE CASCADE
);


Express (Nodejs)



const express = require("express");
const app = express();
const port = 3000;
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "",
user: "",
password: "",
database: "tracker"
});

app.get("/data/:email/metric/:metric", (req, res) => {
console.log(req.params);
let user_id = "";

connection.connect();

connection.query(
`SELECT user_id FROM users WHERE email = '${req.params.email}';`,
function(error, results, fields) {
if (error) throw error;
user_id = results[0].user_id;
}
);

connection.query(
`SELECT users.first_name, users.last_name, users.email, tracking.metric, tracking.unit, tracking.amount, tracking.date_tracked FROM users JOIN tracking ON users.user_id = tracking.user_id WHERE users.user_id = '${user_id}' AND metric = '${
req.params.metric
}';`,
function(error, results, fields) {
if (error) throw error;
res.send(results);
}
);

connection.end();
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));









share|improve this question


























    up vote
    0
    down vote

    favorite












    I am running an Express server and connecting to MySQL Database. I am have two tables which are referenced via the user_id. When the user provides the email address I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this? Also any best practice recommendations for any part of the code is appreciated!



    Thanks



    MySQL



    CREATE TABLE users (
    user_id INT NOT NULL AUTO_INCREMENT UNIQUE,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) DEFAULT NULL,
    email VARCHAR(320) NOT NULL UNIQUE,
    date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id)
    );

    CREATE TABLE tracking (
    tracking_id INT NOT NULL AUTO_INCREMENT,
    user_id INT NOT NULL,
    metric VARCHAR(100) NOT NULL,
    unit VARCHAR(100) NOT NULL,
    amount DOUBLE DEFAULT NULL,
    date_tracked DATE,
    date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (tracking_id),
    INDEX user_ind (user_id),
    FOREIGN KEY (user_id)
    REFERENCES users(user_id)
    ON DELETE CASCADE
    );


    Express (Nodejs)



    const express = require("express");
    const app = express();
    const port = 3000;
    var mysql = require("mysql");
    var connection = mysql.createConnection({
    host: "",
    user: "",
    password: "",
    database: "tracker"
    });

    app.get("/data/:email/metric/:metric", (req, res) => {
    console.log(req.params);
    let user_id = "";

    connection.connect();

    connection.query(
    `SELECT user_id FROM users WHERE email = '${req.params.email}';`,
    function(error, results, fields) {
    if (error) throw error;
    user_id = results[0].user_id;
    }
    );

    connection.query(
    `SELECT users.first_name, users.last_name, users.email, tracking.metric, tracking.unit, tracking.amount, tracking.date_tracked FROM users JOIN tracking ON users.user_id = tracking.user_id WHERE users.user_id = '${user_id}' AND metric = '${
    req.params.metric
    }';`,
    function(error, results, fields) {
    if (error) throw error;
    res.send(results);
    }
    );

    connection.end();
    });

    app.listen(port, () => console.log(`Example app listening on port ${port}!`));









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am running an Express server and connecting to MySQL Database. I am have two tables which are referenced via the user_id. When the user provides the email address I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this? Also any best practice recommendations for any part of the code is appreciated!



      Thanks



      MySQL



      CREATE TABLE users (
      user_id INT NOT NULL AUTO_INCREMENT UNIQUE,
      first_name VARCHAR(100) NOT NULL,
      last_name VARCHAR(100) DEFAULT NULL,
      email VARCHAR(320) NOT NULL UNIQUE,
      date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (user_id)
      );

      CREATE TABLE tracking (
      tracking_id INT NOT NULL AUTO_INCREMENT,
      user_id INT NOT NULL,
      metric VARCHAR(100) NOT NULL,
      unit VARCHAR(100) NOT NULL,
      amount DOUBLE DEFAULT NULL,
      date_tracked DATE,
      date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (tracking_id),
      INDEX user_ind (user_id),
      FOREIGN KEY (user_id)
      REFERENCES users(user_id)
      ON DELETE CASCADE
      );


      Express (Nodejs)



      const express = require("express");
      const app = express();
      const port = 3000;
      var mysql = require("mysql");
      var connection = mysql.createConnection({
      host: "",
      user: "",
      password: "",
      database: "tracker"
      });

      app.get("/data/:email/metric/:metric", (req, res) => {
      console.log(req.params);
      let user_id = "";

      connection.connect();

      connection.query(
      `SELECT user_id FROM users WHERE email = '${req.params.email}';`,
      function(error, results, fields) {
      if (error) throw error;
      user_id = results[0].user_id;
      }
      );

      connection.query(
      `SELECT users.first_name, users.last_name, users.email, tracking.metric, tracking.unit, tracking.amount, tracking.date_tracked FROM users JOIN tracking ON users.user_id = tracking.user_id WHERE users.user_id = '${user_id}' AND metric = '${
      req.params.metric
      }';`,
      function(error, results, fields) {
      if (error) throw error;
      res.send(results);
      }
      );

      connection.end();
      });

      app.listen(port, () => console.log(`Example app listening on port ${port}!`));









      share|improve this question













      I am running an Express server and connecting to MySQL Database. I am have two tables which are referenced via the user_id. When the user provides the email address I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this? Also any best practice recommendations for any part of the code is appreciated!



      Thanks



      MySQL



      CREATE TABLE users (
      user_id INT NOT NULL AUTO_INCREMENT UNIQUE,
      first_name VARCHAR(100) NOT NULL,
      last_name VARCHAR(100) DEFAULT NULL,
      email VARCHAR(320) NOT NULL UNIQUE,
      date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (user_id)
      );

      CREATE TABLE tracking (
      tracking_id INT NOT NULL AUTO_INCREMENT,
      user_id INT NOT NULL,
      metric VARCHAR(100) NOT NULL,
      unit VARCHAR(100) NOT NULL,
      amount DOUBLE DEFAULT NULL,
      date_tracked DATE,
      date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (tracking_id),
      INDEX user_ind (user_id),
      FOREIGN KEY (user_id)
      REFERENCES users(user_id)
      ON DELETE CASCADE
      );


      Express (Nodejs)



      const express = require("express");
      const app = express();
      const port = 3000;
      var mysql = require("mysql");
      var connection = mysql.createConnection({
      host: "",
      user: "",
      password: "",
      database: "tracker"
      });

      app.get("/data/:email/metric/:metric", (req, res) => {
      console.log(req.params);
      let user_id = "";

      connection.connect();

      connection.query(
      `SELECT user_id FROM users WHERE email = '${req.params.email}';`,
      function(error, results, fields) {
      if (error) throw error;
      user_id = results[0].user_id;
      }
      );

      connection.query(
      `SELECT users.first_name, users.last_name, users.email, tracking.metric, tracking.unit, tracking.amount, tracking.date_tracked FROM users JOIN tracking ON users.user_id = tracking.user_id WHERE users.user_id = '${user_id}' AND metric = '${
      req.params.metric
      }';`,
      function(error, results, fields) {
      if (error) throw error;
      res.send(results);
      }
      );

      connection.end();
      });

      app.listen(port, () => console.log(`Example app listening on port ${port}!`));






      mysql node.js express






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 at 16:33









      lukechambers91

      416




      416
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          You can accomplish this with a single query, just JOIN the tables on user_id



          SELECT 
          u.first_name,
          u.last_name,
          u.email,
          t.metric,
          t.unit,
          t.amount,
          t.date_tracked
          FROM users u
          INNER JOIN tracking AS t ON t.user_id = u.user_id
          WHERE u.email = '<email>' AND t.metric = '<metric>'


          Also, FWIW you should use parameterised queries to protect yourself from SQL Injection



          const values = [
          req.params.email,
          req.params.metric
          ];
          connection.query(
          'SELECT ... WHERE u.email = ? AND t.metric = ?',
          values,
          (err, results, fields) => {
          if (err) return next(e); // propagate the error to Express, rather than throwing in the callback

          res.send(results);
          }
          );





          share|improve this answer























          • Thanks this was very informative and helpful!
            – lukechambers91
            Nov 22 at 23:33


















          up vote
          1
          down vote














          I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this?




          You can achieve it with only 1 query:



              SELECT users.first_name, users.last_name, users.email, 
          tracking.metric, tracking.unit, tracking.amount,
          tracking.date_tracked
          FROM users
          JOIN tracking
          ON users.user_id = tracking.user_id
          WHERE users.email = '${req.params.email}' AND
          metric = '${req.params.metric}



          Also any best practice recommendations for any part of the code is appreciated!




          First of all, you should connect to mySql after the server as started .



          Connecting&Disconnecting on each request will impact the performance(It's expensive task opening a socket and connecting outside)



          so try something like :



              CONNECTION.connect().then(() => {
          // mysql is ready , let's start express server
          // accepting connections
          app.listen(port, () => console.log(`ready on ${port}!`));
          }).catch(console.error)


          Another good practice you should know is running queries in parallel
          with Promise.all(). when you need to run multiple , unrelated queries ,
          you can Execute them all one after the other , making the total wait time for all results much smaller .






          share|improve this answer





















            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',
            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%2f53435087%2fmultiple-mysql-queries-with-express-node%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            You can accomplish this with a single query, just JOIN the tables on user_id



            SELECT 
            u.first_name,
            u.last_name,
            u.email,
            t.metric,
            t.unit,
            t.amount,
            t.date_tracked
            FROM users u
            INNER JOIN tracking AS t ON t.user_id = u.user_id
            WHERE u.email = '<email>' AND t.metric = '<metric>'


            Also, FWIW you should use parameterised queries to protect yourself from SQL Injection



            const values = [
            req.params.email,
            req.params.metric
            ];
            connection.query(
            'SELECT ... WHERE u.email = ? AND t.metric = ?',
            values,
            (err, results, fields) => {
            if (err) return next(e); // propagate the error to Express, rather than throwing in the callback

            res.send(results);
            }
            );





            share|improve this answer























            • Thanks this was very informative and helpful!
              – lukechambers91
              Nov 22 at 23:33















            up vote
            1
            down vote



            accepted










            You can accomplish this with a single query, just JOIN the tables on user_id



            SELECT 
            u.first_name,
            u.last_name,
            u.email,
            t.metric,
            t.unit,
            t.amount,
            t.date_tracked
            FROM users u
            INNER JOIN tracking AS t ON t.user_id = u.user_id
            WHERE u.email = '<email>' AND t.metric = '<metric>'


            Also, FWIW you should use parameterised queries to protect yourself from SQL Injection



            const values = [
            req.params.email,
            req.params.metric
            ];
            connection.query(
            'SELECT ... WHERE u.email = ? AND t.metric = ?',
            values,
            (err, results, fields) => {
            if (err) return next(e); // propagate the error to Express, rather than throwing in the callback

            res.send(results);
            }
            );





            share|improve this answer























            • Thanks this was very informative and helpful!
              – lukechambers91
              Nov 22 at 23:33













            up vote
            1
            down vote



            accepted







            up vote
            1
            down vote



            accepted






            You can accomplish this with a single query, just JOIN the tables on user_id



            SELECT 
            u.first_name,
            u.last_name,
            u.email,
            t.metric,
            t.unit,
            t.amount,
            t.date_tracked
            FROM users u
            INNER JOIN tracking AS t ON t.user_id = u.user_id
            WHERE u.email = '<email>' AND t.metric = '<metric>'


            Also, FWIW you should use parameterised queries to protect yourself from SQL Injection



            const values = [
            req.params.email,
            req.params.metric
            ];
            connection.query(
            'SELECT ... WHERE u.email = ? AND t.metric = ?',
            values,
            (err, results, fields) => {
            if (err) return next(e); // propagate the error to Express, rather than throwing in the callback

            res.send(results);
            }
            );





            share|improve this answer














            You can accomplish this with a single query, just JOIN the tables on user_id



            SELECT 
            u.first_name,
            u.last_name,
            u.email,
            t.metric,
            t.unit,
            t.amount,
            t.date_tracked
            FROM users u
            INNER JOIN tracking AS t ON t.user_id = u.user_id
            WHERE u.email = '<email>' AND t.metric = '<metric>'


            Also, FWIW you should use parameterised queries to protect yourself from SQL Injection



            const values = [
            req.params.email,
            req.params.metric
            ];
            connection.query(
            'SELECT ... WHERE u.email = ? AND t.metric = ?',
            values,
            (err, results, fields) => {
            if (err) return next(e); // propagate the error to Express, rather than throwing in the callback

            res.send(results);
            }
            );






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 at 17:06

























            answered Nov 22 at 16:41









            James

            59.3k16119193




            59.3k16119193












            • Thanks this was very informative and helpful!
              – lukechambers91
              Nov 22 at 23:33


















            • Thanks this was very informative and helpful!
              – lukechambers91
              Nov 22 at 23:33
















            Thanks this was very informative and helpful!
            – lukechambers91
            Nov 22 at 23:33




            Thanks this was very informative and helpful!
            – lukechambers91
            Nov 22 at 23:33












            up vote
            1
            down vote














            I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this?




            You can achieve it with only 1 query:



                SELECT users.first_name, users.last_name, users.email, 
            tracking.metric, tracking.unit, tracking.amount,
            tracking.date_tracked
            FROM users
            JOIN tracking
            ON users.user_id = tracking.user_id
            WHERE users.email = '${req.params.email}' AND
            metric = '${req.params.metric}



            Also any best practice recommendations for any part of the code is appreciated!




            First of all, you should connect to mySql after the server as started .



            Connecting&Disconnecting on each request will impact the performance(It's expensive task opening a socket and connecting outside)



            so try something like :



                CONNECTION.connect().then(() => {
            // mysql is ready , let's start express server
            // accepting connections
            app.listen(port, () => console.log(`ready on ${port}!`));
            }).catch(console.error)


            Another good practice you should know is running queries in parallel
            with Promise.all(). when you need to run multiple , unrelated queries ,
            you can Execute them all one after the other , making the total wait time for all results much smaller .






            share|improve this answer

























              up vote
              1
              down vote














              I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this?




              You can achieve it with only 1 query:



                  SELECT users.first_name, users.last_name, users.email, 
              tracking.metric, tracking.unit, tracking.amount,
              tracking.date_tracked
              FROM users
              JOIN tracking
              ON users.user_id = tracking.user_id
              WHERE users.email = '${req.params.email}' AND
              metric = '${req.params.metric}



              Also any best practice recommendations for any part of the code is appreciated!




              First of all, you should connect to mySql after the server as started .



              Connecting&Disconnecting on each request will impact the performance(It's expensive task opening a socket and connecting outside)



              so try something like :



                  CONNECTION.connect().then(() => {
              // mysql is ready , let's start express server
              // accepting connections
              app.listen(port, () => console.log(`ready on ${port}!`));
              }).catch(console.error)


              Another good practice you should know is running queries in parallel
              with Promise.all(). when you need to run multiple , unrelated queries ,
              you can Execute them all one after the other , making the total wait time for all results much smaller .






              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote










                I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this?




                You can achieve it with only 1 query:



                    SELECT users.first_name, users.last_name, users.email, 
                tracking.metric, tracking.unit, tracking.amount,
                tracking.date_tracked
                FROM users
                JOIN tracking
                ON users.user_id = tracking.user_id
                WHERE users.email = '${req.params.email}' AND
                metric = '${req.params.metric}



                Also any best practice recommendations for any part of the code is appreciated!




                First of all, you should connect to mySql after the server as started .



                Connecting&Disconnecting on each request will impact the performance(It's expensive task opening a socket and connecting outside)



                so try something like :



                    CONNECTION.connect().then(() => {
                // mysql is ready , let's start express server
                // accepting connections
                app.listen(port, () => console.log(`ready on ${port}!`));
                }).catch(console.error)


                Another good practice you should know is running queries in parallel
                with Promise.all(). when you need to run multiple , unrelated queries ,
                you can Execute them all one after the other , making the total wait time for all results much smaller .






                share|improve this answer













                I need to query users to find the user_id then run another query to join the tracking tables. What is the best way to achieve this?




                You can achieve it with only 1 query:



                    SELECT users.first_name, users.last_name, users.email, 
                tracking.metric, tracking.unit, tracking.amount,
                tracking.date_tracked
                FROM users
                JOIN tracking
                ON users.user_id = tracking.user_id
                WHERE users.email = '${req.params.email}' AND
                metric = '${req.params.metric}



                Also any best practice recommendations for any part of the code is appreciated!




                First of all, you should connect to mySql after the server as started .



                Connecting&Disconnecting on each request will impact the performance(It's expensive task opening a socket and connecting outside)



                so try something like :



                    CONNECTION.connect().then(() => {
                // mysql is ready , let's start express server
                // accepting connections
                app.listen(port, () => console.log(`ready on ${port}!`));
                }).catch(console.error)


                Another good practice you should know is running queries in parallel
                with Promise.all(). when you need to run multiple , unrelated queries ,
                you can Execute them all one after the other , making the total wait time for all results much smaller .







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 at 16:53









                Amit Triffon

                112




                112






























                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53435087%2fmultiple-mysql-queries-with-express-node%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

                    What visual should I use to simply compare current year value vs last year in Power BI desktop

                    How to ignore python UserWarning in pytest?

                    Alexandru Averescu