Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mariadb

web

colt

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.

like image 642
Shutter Avatar asked Aug 24 '18 01:08

Shutter


People also ask

Which database should I use with Express?

What databases can I use? Express apps can use any database supported by Node (Express itself doesn't define any specific additional behavior/requirements for database management). There are many popular options, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.

CAN node JS interact with database?

Node.js can be used in database applications. One of the most popular databases is MySQL.


2 Answers

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
    });
like image 152
markusjm Avatar answered Sep 26 '22 02:09

markusjm


Sequelize

npm install --save sequelize@next
npm install --save mariadb

Then set dialect: 'mariadb'

The mariadb connector is much faster than MySQL2. I noticed the speed difference immediately on my platform.

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

MariaDB provides benchmarks comparing the Connector with popular Node.js MySQL clients, including:

promise-mysql version 3.3.1 + mysql version 2.15.0 mysql2 version 1.5.3

promise-mysql  : 1,366 ops/sec ±1.42%
mysql2         : 1,469 ops/sec ±1.63%
mariadb        : 1,802 ops/sec ±1.19%
like image 42
buycanna.io Avatar answered Sep 25 '22 02:09

buycanna.io