# \[Tutorial\] How to Use MySQL or MariaDB with Node.js and Express

**URL:** <https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260>\
**Category:** Tutorials\
**Tags:** javascript\
**Created:** [April 26, 2020, 1:49am UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260 "2020-04-26T01:49:04Z")\
**Posts on this page:** 18\
**Page:** 2

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 8:26pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/21 "2020-04-28T20:26:17Z")

</div>

I guess what I asking is: does the handlebars template get populated server side or client side?  
That is what I meant by missing hbs… “missing” would be the template variable.

Redis sounds awesome.  
I would love a tutorial on how to deploy this stack and use redis. I am probably at least a week from doing that though.

About the partials, I agree. I tried adding them to the view controller files, but you have to change the directory and then you also have to keep adding them. Having the partials listed in the server.js (app.js) keeps them centralized and you only write them one time! 🙂

Oh, someone also mentioned helper function to me. I guess those would “help” the controller files change data before being displayed. Are those usually kept in a sub-folder of the controller?

Also also, I changed the database folder to the “models” name as I understand that is the roll of the database in the Model/View/Controller programming structure.

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 8:57pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/22 "2020-04-28T20:57:37Z")

</div>

> [@PaulH](#):
>
> I guess what I asking is: does the handlebars template get populated server side or client side?  
> That is what I meant by missing hbs… “missing” would be the template variable.

Handlebars can run on the server or the client. In the Express app, it only runs on the server. In this forum it runs on the client.

> [@PaulH](#):
>
> I would love a tutorial on how to deploy this stack and use redis.

I’ll post those soon.

> [@PaulH](#):
>
> Oh, someone also mentioned helper function to me. I guess those would “help” the controller files change data before being displayed. Are those usually kept in a sub-folder of the controller?

You can make two more directories:

- `helpers`
- `middleware`

Helpers could contain things like reusable functions for converting measurements.

Middleware probably comes later.

> [@PaulH](#):
>
> I changed the database folder to the “models” name as I understand that is the roll of the database in the Model/View/Controller programming structure.

You can put all those functions like `getMonsterById` in a `./models/monster.js` file. You can put the database connection (`pool`) in something like a `db.js` file that each model file can import. I haven’t used this package on my own sites, but I think that will work.

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:01pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/23 "2020-04-28T21:01:59Z")

</div>

Ah yes, the db.js like in this guide works great!

I will look into adding a helpers folder.

Look forward to the tutorials!  
Thanks!

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:12pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/24 "2020-04-28T21:12:52Z")

</div>

Small note, if you want to get URL parameters from a URL as such  
`nutrition-facts.php?food=174682`

Then you can use `req.query`  
as in  
`const foodId = req.query.food;`

The router query doesn’t need to define the parameters  
`router.get("/nutrition-facts.php", ctrl.nutritionFacts);`

Sample usage in a controller

````auto
function nutritionFacts(req, res) {
    const foodId = req.query.food;
    console.log(foodId);
    db.getDataById(foodId, foodId, foodId)
        .then(data => {

            //Calculations and logic go here

            // console.log("data", data[0]);
            // const {fdc_id,name3} = data[0];
            // console.log(fdc_id);
            const foodData = data[0]; // optionally edit data[0] here.

res.render("./tools/nutrition-facts.hbs", {
    custom: "Custom Title",
    foodData: foodData, // now foodData.fdc_id, etc. are available in the template
});
        })
        .catch(err => {
            // if you want anything to happen when there is an error, put it here

            // this gets sent back if there is an error
            res.status(500).json(err);
        });
    // Don't put anything down here.
}```
````

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 9:18pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/25 "2020-04-28T21:18:08Z")

</div>

If you want to keep the URLs exactly the same, you can do this with `req.query`:

```nohighlight
/nutrition-facts.php?food=174682

```

If you use `req.params`, then you can make URLs like this…

```nohighlight
/nutrition-facts/food/174682

```

or if you have something like this…

```nohighlight
nutrition-facts.php?food=174682?other-thing=abc

```

which creates duplicate content at…

```nohighlight
nutrition-facts.php?other-thing=abc?food=174682

```

`req.params` would be able to redirect both versions to a single canonical version:

```nohighlight
nutrition-facts/food/174682/other-thing/abc

```

(That’s actually an example of where middleware could be used. It could check for query parameters on the request and then do redirects to canonical locations.)

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:20pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/26 "2020-04-28T21:20:11Z")

</div>

Hmm I think I want to go for the better req.params link structure, but then I will need a way to forward the legacy links that use req.query.

For now I think it is simpler to keep the existing structure, then create a redirect to the new structure later…

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 9:25pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/27 "2020-04-28T21:25:01Z")

</div>

I added to my comment above. I was mentioning that middleware could be used to do the redirects. The middleware could be inserted before the routers.

```javascript
// something like this (untested)
app.use((req, res, next) => {
    const { food, otherQueryString } = req.query;

    // if the query strings are there, redirect to the canonical version
    if (food && otherQueryString) {
        res.redirect(301, `/food/${food}/${otherQueryString}`);
    }

    // If the query strings weren't found, then go to the
    // next middleware (router)
    next();
});

```

It might be simpler to keep it as-is, but also wouldn’t be that difficult to do the redirects. 🙂

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:27pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/28 "2020-04-28T21:27:37Z")

</div>

OK, so I would  
`router.get("/nutrition-facts.php", ctrl.nutritionFacts);`

But instead of ctrl.nutritionFacts I would call the redirect function above?

And then that redirect function would call  
`router.get("/nutrition-facts/", ctrl.nutritionFacts);` ?

Hmm, I am going to try re-create things and then clean up stuff like that. Otherwise… 🤕 😉

Thanks for letting me know though. It is good to know that a redirect will not be too tough.

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 9:28pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/29 "2020-04-28T21:28:50Z")

</div>

Testing would be useful there. I can add a tutorial on testing that with Cypress at some point.

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 9:33pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/30 "2020-04-28T21:33:57Z")

</div>

Maybe something like this?

```javascript
const ctrl = require("../controllers/nutritionFactsController");

// This could be your main nutrition facts page
router.get("/nutrition-facts", ctrl.index);

// This template would handle the "detail view" for each specific food (by ID)
// `:foodId` would be available in the controller as `req.params.foodId`.
router.get("/nutrition-facts/:foodId", ctrl.detail);

```

Then in the controller:

```javascript
// not exactly this, but just illustrating an idea
const Food = require("../models/food");

function list(req, res) {
    res.render("nutrition-facts/list", { title: "Nutrition Facts" });
}

function detail(req, res) {
    const foodId = req.params.foodId;
    Food.getFoodById(foodId)
        .then(data => {
            res.render("nutrition-facts/detail", { title: data.foodName });
        });
}

module.exports = {
    list,
    detail,
};

```

If you want me to take a look at anything over screensharing, send a chat message any time.

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:40pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/31 "2020-04-28T21:40:11Z")

</div>

Hmm, looks about right.

Right now though, I am more interested in using helper functions.

I am going to need to process the data that comes in from the db before sending it to the view.

Any good examples? I will also search around.

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 9:44pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/32 "2020-04-28T21:44:42Z")

</div>

> [@PaulH](#):
>
> I am going to need to process the data that comes in from the db before sending it to the view.

You can put reusable, miscellaneous functions in a directory named `helpers`.

Example:

`helpers/conversions.js`

```javascript
function ouncesToQuarts(oz) {
    return oz * 0.03125;
}

module.exports = {
    ouncesToQuarts,
};

```

Then in another file that wants to use that function:

```javascript
// require the conversions module
const conversions = require("../helpers/conversions");

// use the module's functions
conversions.ouncesToQuarts(100);

```

Is that the kind of example you’re looking for?

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:46pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/33 "2020-04-28T21:46:13Z")

</div>

I think that is it exactly! Thanks!  
I am going to try it and will report back!

Should the helpers folder be a subfolder of controllers? I guess so…or maybe it doesn’t matter

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [April 28, 2020, 9:50pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/34 "2020-04-28T21:50:28Z")

</div>

The `helpers` directory wouldn’t have any controller files in it — I’d keep all of the controllers in `controllers`. But if you have functions that are used in multiple controllers, then you could put those in `helpers` and import them into every file that needs to use them.

Controllers are the functions that take `request` and `response`. If a function has those two parameters, it should probable go in either `controllers` or `middleware`. If the function doesn’t have those two parameters, then `helpers` might be a place for it.

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [April 28, 2020, 9:54pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/35 "2020-04-28T21:54:28Z")

</div>

Got it, thanks! 🙂

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [May 5, 2020, 7:14pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/36 "2020-05-05T19:14:47Z")

</div>

I have a question now wondering how you can query MySQL when you will have to make multiple parameters.

For example a user may have 2-30 foods in a recipe, so I will have to query the table for each food.  
What is the best way to do this with Node?

From what I understand I should put all parameters in an array and loop through it and then use `promise.all`

This code from stack overflow looks promising

```auto
var promises = [];

array.forEach(function(element) {
    promises.push(
        developer.getResources(element)
            .then((data) = > {
                name = data.items[0];
                return developer.getResourceContent(element, file);
            })
            .then((response) = > {
                fileContent = atob(response.content);
                self.files.push({
                    fileName: fileName,
                    fileType: fileType,
                    content: fileContent
                });
            }).catch ((error) = > {
                console.log('Error: ', error);
            })
    );
});

Promise.all(promises).then(() => 
    self.resultingFunction(self.files)
);

```

> <https://stackoverflow.com/questions/38362231/how-to-use-promise-in-foreach-loop-of-array-to-populate-an-object/38362312#38362312>

And then my friend also shared one with mapping

```auto
// map array of values to a query
const mapValues = async (queryText, array) => {
  const client = await pool.connect();
  const results = [];
  const queryDB = async value => {
    try {
      const { rows } = await pool.query(queryText, value);
      if (rows.length > 0) {
        results.push(rows[0]);
      }
    } catch (error) {
      client.release();
      throw error;
    }
  };
  await Promise.all(array.map(value => queryDB(value)));
  client.release();
  return results;
};

```

But I am having trouble getting it to work. What is the best solution to this given this kind of routing with node and express?

---

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [May 5, 2020, 7:55pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/37 "2020-05-05T19:55:38Z")

</div>

> [@PaulH](#):
>
> For example a user may have 2-30 foods in a recipe, so I will have to query the table for each food.

Can you do something like this in one query?

```sql
-- 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:

```javascript
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:

```javascript
// 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.

```javascript
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. 🙂

---

<div class="post-metadata">

**Author:** ![PaulH](https://forum.codeselfstudy.com/letter_avatar_proxy/v4/letter/p/e495f1/32.png) [@PaulH](https://forum.codeselfstudy.com/u/PaulH)\
**Post date:** [May 5, 2020, 8:37pm UTC](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260/38 "2020-05-05T20:37:56Z")

</div>

Great suggestion. To using the `in` statement is way faster. I just clocked 200 ids with php.

 ![loop-vs-in-statement](https://forum.codeselfstudy.com/uploads/default/original/2X/a/aa2395bbf6a75a1a33ddef37c55b0b546cbb9f33.png)

100ms vs 4ms… 😃 No brainer.  
I will let you know how it works out.

[Previous page](https://forum.codeselfstudy.com/t/tutorial-how-to-use-mysql-or-mariadb-with-node-js-and-express/2260.md?page=1)
