I have the following code in my db.js file:
const mysql2 = require('mysql2/promise');
// Connect to server (locally for development mode) ----- NEW VERSIN
const pool = mysql2.createPool({
host : "ENDPOINT",
user : "admin",
password : "PASSWORD",
port : "3306",
database : "DATABASE",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool;
And in my app.js file I have:
const pool = require('./db');
async function checkUser(username) {
const result = await pool.query('SELECT * from users WHERE username = ?', [username]);
if (result[0].length < 1) {
throw new Error('Row with this username was not found');
}
return result[0][0];
}
async function check() {
let user = await checkUser("username");
console.log(user);
}
check(); But I'm getting the error:
(node:42037) UnhandledPromiseRejectionWarning: TypeError: pool.query is not a function
This is weird, because when I run all the code in the db.js file it works fine, so I'm probably messed up the export/require bit of it, please help!
ANSWER: HOW TO EXPORT MULTIPLE FUNCTIONS
In the document you are exporting, write as follows:
module.exports = {FunctionName1, FunctionName2, FunctionName3};
In the document you are importing to, write the following:
const {FunctionName1, FunctionName2, FunctionName3} = require('./whereyouareimportingfrom');
I had done the exports the wrong way, I tried exporting two functions by doing: "module.exports = ConnectDb, pool;" And that didn't work. When I removed the first function and only exported "pool" it worked.