How do I connect MariaDB to Node.JS and Express.JS?

Shutter picture Shutter · Aug 24, 2018 · Viewed 17.3k times · Source

I'm doing Colt Steele's The Web Developer Bootcamp and I've got to the point where we're going to start a database for the YelpCamp app. Problem is, he is using MongoDB, and I don't want to use that. I want to use MariaDB. How can I get Node JS to work with it? I've already added it to my project using npm install, but I've got no idea where to go from here. I can't find any guides pertaining specifically to nodejs and mariadb. The official guide is not beginner friendly. I have no idea what alot of it even says.

I'm not working thorugh Cloud9 like he is because they're not accepting new registrations. I am running node.js on my computer using the command line, and have been following his videos that way.

Answer

markusjm picture markusjm · Aug 24, 2018

https://github.com/MariaDB/mariadb-connector-nodejs

Install: npm i mariadb

const mariadb = require('mariadb');
const pool = mariadb.createPool({host: 'mydb.com', user: 'myUser', connectionLimit: 5});
pool.getConnection()
    .then(conn => {
      conn.query("SELECT 1 as val")
        .then((rows) => {
          console.log(rows); //[ {val: 1}, meta: ... ]
          return conn.query("INSERT INTO myTable value (?, ?)", [1, "mariadb"]);
        })
        .then((res) => {
          console.log(res); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
          conn.end();
        })
        .catch(err => {
          //handle error
          conn.end();
        })
    }).catch(err => {
      //not connected
    });