Skip to main content

DBConnection

Connect to mySQL

//first we install mysql package
$ npm install mysql
//then we can use package to connect
const mysql = require('mysql');
const conn = mysql.createConnection({
host: 'localhost',
user: 'dbuser',
password: '123456',
database: 'mydb'
})

conn.connect();

conn.query("SELECT * FROM product", (err, rows, fields) => {
if (err) throw err;
console.log('The solution is: ', rows)
})

connection.end()

Pool of mySQL connections

var mysql = require('mysql');
//create connection pool to database
var pool = mysql.createPool({
host:"localhost",
port:3307,
user:"apiuser",
password:"123456",
database:"jrt"
})
pool.getConnection((err,connection)=> {
if(err)throw err;
console.log('Company Database connected successfully');
connection.release();
});
module.exports = pool;

Connect to MongoDB

//first we install mongodb package
$ npm i mongodb
//then we can use package to connect
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mydb', (err, db) => {
if (err) throw err;
db.collection('products').find().toArray((err, result) => {
if (err) throw err;
console.log(result);
})
})

create module db.js using Mongoose

//first we install mongoose package
$ npm i mongoose
//then we can use package to connect
const mongoose = require('mongoose');
const connectDB = async () =>{
const conn = await mongoose.connect('mongodb://localhost:27017/mydb');
console.log('mongodb connected: ' + conn.connection.host);
}
module.exports = connectDB;

//then in index.js
const connectDB = require('./src/routes/db');
connectDB();
app.use('/products',products);