Databases and NodeJS

Databases are super important if you would like to store data. You can use it to store shop items, user statistics, mini-game data, and more! Databases are extremely useful for Discord bots and this is why you should learn how to connect to a database in NodeJS.

Since you are going to use MySQL, you will need to install the mysql package to your project.

Start of by adding the following code into a new file in your project. In this case, you will name this file connect.js.

const mysql = require('mysql')

const connection = mysql.createPool({
    host: "1.2.3.4",
    user: "username",
    password: "password",
    database: "database"
})

module.exports = connection

Since you exported the connection from the connect.js file, you are able to import it to other files in the project and use the connection. Here is an example of how to use the connection.

const connection = require('./connect.js')
const id = "398514225435377673"

connection.query(`SELECT * FROM characters WHERE discordId = ?`, [id], function (err, result) {
    if (err) {
            console.log(err)
    }

    console.log(result[0])
})

To keep your project clean, you are able to have all of your database functions in a single file and export those function for further use in other parts of your project. In thise case, you have this piece of code in a file called databaseFunctions.js. Here is an example:

// databaseFunctions.js
const connection = require('./connect.js')

exports.getUser= async function (id) {
    return new Promise((resolve, reject) => {

        connection.query(`SELECT * FROM users WHERE discordId = ?`, [id], function (err, result) {
            if (err) {
                log.error(err)
                reject(err)
            }

            resolve(result)
        })
    })
}

// otherFile.js

const databaseQuery = require('databaseFunctions.js')
const id = "398514225435377673"

//Method 1
const userInfo = await databaseQuery.getUser(id)
console.log(userInfo)

//Method 2
databaseQuery.getUser(id).then((userInfo) => {
    console.log(userInfo)
}).catch((err) => {
    conslle.log(err)
})

If you have any questions, please contact us for support.

Last updated