2

I have only been working with PHP before going to Node.JS. What I was able to do in PHP when working with MYSQL was that I could include the database.php file in the files I wanted to execure queries in.

It doesn't seem to be the same in Node.Js. This is my database.js file

const mysql  = require("mysql2/promise");

const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'XXXX',
    database: 'nodelogin'
});

module.exports = db;

Then I require this in my file login.js

const db  = require("../../database");

However, when I then try to run db.query(sql, [variable]) I get db.query is not a function.

Why is this? It shouldn't be that more complicated or should it?

2

1 Answer 1

2

If you use a connection pool instead, you can include the pool once, then call query on it, like so:

db-config.js

const mysql = require("mysql2/promise");

console.log("Creating connection pool...")
const pool = mysql.createPool({
    host: 'localhost',
    user: 'user',
    database: 'test_db',
    password: 'password'
})

module.exports = pool;

test.js

// Require to whereever db-config is 
const pool = require('./db-config.js');

async function testQuery() {
    const results = await pool.query("select * from users");
    console.table(results[0]);
}

testQuery();
Sign up to request clarification or add additional context in comments.

3 Comments

doing it this way, require is cached, but on multiple places like inside express handlers will quickly hammer connections, anti-pattern
but this means I have to include "database.js" in every query I make? Isn't there a way to just include it once in each file?
Good point @LawrenceCherone, I've updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.