I'm developing an application with node.js and in login form I ask user to select the database but I don't know how to set the connection with the selected database.
How can I put several connections in my config.js?
And how can I set a connection wit a selected database?
var mssql = require("mssql");
var config =
{
user: "user",
password: "password",
server: "IP",
database: "db_name"
}
var db = new mssql.Connection(config);
db.connect(function(err)
{
console.log(err);
});
module.exports = db;
Thank you
To do this, you can just make two database connections
var mssql = require("mssql");
var config =
{
user: "user",
password: "password",
server: "IP",
database: "db_name"
}
var db = new mssql.Connection(config);
var db2 = new mssql.Connection(config);
db.connect(function(err)
{
console.log(err);
});
db2.connect(function(err)
{
console.log(err);
});
module.exports = {db: db, db2: db2};
If you need a separate config, you can just make two configs. To use the first db, just require("config").db and the second db is at require("config").db2
Related
Im learning from a ready application and im trying to make the connection so the app to start working and save data.
picture of the hostname and port
I done the connectin also make a 'employees database' with the two tables that I need
picture of the schema
The server is running on localhost 3000 and the front end is listening on port 4200. This is the code for the connection and creating the database/schema.
config.json
{
"host": "localhost",
"user": "cveto",
"database": "employees",
"password": "1234567"
}
database.js creating pool
const mysql = require('mysql2');
const config = require('../config/config.json');
const pool = mysql.createPool({
host: config.host,
user: config.user,
database: config.database,
password: config.password,
});
module.exports = pool.promise();
And some query models
const db = require('../util/database');
module.exports = class Employee {
constructor(names, address, number, salary) {
this.names = names;
this.address = address;
this.number = number;
this.salary = salary;
}
static fetchAll() {
return db.execute('SELECT * FROM employees');
}
static save(employee) {
return db.execute(
'INSERT INTO employees (names, address, number, salary) VALUES (?, ?, ?, ?)',
[employee.names, employee.address, employee.number, employee.salary]
);
}
static delete(id) {
return db.execute('DELETE FROM employees WHERE id = ?', [id]);
}
};
I just want to know how I can make the connection so the app to work and save to my database the users and new employees. The code is from public repositority so the code is working, its now from the code its from tha database or server conncetion.
DB.js File
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 100,
host : 'localhost',
user : 'root',
password : '',
database : '',
});
let myDb = {};
myDb.searchDataQ = (query) => {
return new Promise((resolve, reject) => {
pool.query(query, function (err, rows) {
if (err) {
reject(err);
}
resolve(rows)
})
});
};
module.exports = myDb;
Other JS File to execute
const db = require('../db/db');
function testMethod() {
let query = 'SELECT * FROM employees';
return new Promise(async (resolve, reject) => {
try {
resolve(await db.searchDataQ(query));
} catch (e) {
reject(0);
}
});
}
When I run the server attempting to create two databases (db1 and db2), the system kicks backs this error:
Possibly unhandled SequelizeBaseError: database "db2" does not exist
As a reference, there is similar stackoverflow question on this topic here, however, the author of the solution does not cover the solution to how the server.js file is setup. You will notice I have structured my index.js file similar to their answer.
My models/index.js file and server run and executes scripts properly, yet the second database does not work at all and does not even get initialized.
Can someone provide a solution for the server.js file to accurately initialize two databases in this one server?
The following is the partial code from the models/index.js and server.js files. In the server.js file, I am using .sync to initialize the databases.
server.js
[...]
//sync's sequelize DB and tables
db['db1'].sequelize.sync(function(err){});
db['db2'].sequelize.sync(function(err){});
models/index.js
var databasesArray = ['db1', 'db2']
var databasesObj = {
database: {
db1: {
DBName: 'db1',
User: user,
Password: password,
Config: config,
},
db2: {
DBName: 'db2',
User: user,
Password: password,
Config: config,
}
}
} // EOF databaseObj
for(var i = 0; i < databasesArray.length; ++i) {
var databasePointerToOBJ = databasesArray[i];
var database = databasesObj.database[databasePointerToOBJ]
if(database.DBName == 'db1'){
var sq = new Sequelize(database.DBName, user, password, config)
db['db1'] = {
Sequelize: Sequelize,
sequelize: sq,
Table1: sq.import(__dirname + '/...')
}
}else if(database.DBName == 'db2'){
var sq = new Sequelize(database.DBName, user, password, config)
db['db2'] = {
Sequelize: Sequelize,
sequelize: sq,
Table1: sq.import(__dirname + '/...')
}
}
}
module.exports = db;
--- EDIT ---
The author of the solution was correct. In order for a new database to be created, it must be created prior to being sync'd. As piotrbienias rightly notes, adding the code for adding a new DB in a your initialization script would be the best option. Piotrbienias solution is .js option. The code that worked for me is a .sh option and is as following:
PG_HOST=localhost
PG_PORT=5432
PG_DB=databaseName
PG_USER=ubuntu
PG_PASS='EnterPassword'
sudo -u postgres createdb -U postgres -O $PG_USER $PG_DB
You need to create the database manually before trying to access it via Sequelize - it does not create it if it does not exists. You can use a pg module inside some initialisation script to create the DB via CREATE DATABASE before doing any synchronisation and connection, or simply create it via postgres CLI
const pg = require('pg');
module.exports = function(next){
var connectionData = {
user: 'postgres',
password: 'password',
host: 'localhost'
};
var databaseName = 'db2';
var connectionUri = `postgres://${user}:${password}#${host}/postgres`;
pg.connect(connectionUri, function(err, client, done) {
client.query(`CREATE DATABASE ${databaseName}`, function(error){
// here you can perform some sequelize operations after creating the database
client.end(); // disconnect client
next(); // you can call it with some parameter like Sequelize instance etc.
});
});
};
I am currently developing a node.js backend for a mobile app with potentially many users. However it's my first time in developing node.js. I was following a tutorial on how to connect to a mysql database via mysql pools.
I am able to create a single mysql connection and do queries via my routes.
The problem arises once I establish the file structure mentioned in the tutorial:
dbConnect
-[models]
--users.js
-db.js
-server-ks
I am not getting an error message regarding the connection of the mysql database - even if I enter a wrong password.
// server.js
///////////////////////////// basic setup ///////////////////////////////////
var restify = require('restify');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var db = require('./db');
var users = require('./models/users');
///////////////////////////// initilisation of the server ///////////////////////////////////
var server = restify.createServer({
name: 'testUsers',
});
server.use(restify.bodyParser({ mapParams: true }));
///////////////////////////// Säuberung der URL //////////////////////////////////////////
server.pre(restify.pre.sanitizePath());
///////////////////////////// MySQL Instanz starten //////////////////////////////////////////
db.connect(db.MODE_PRODUCTION, function (err) {
if (err) {
console.log('Unable to connect to MySQL.')
process.exit(1)
} else {
server.listen(8080, function () {
console.log('Listening on port 8080 ...')
})
}
})
///////////////////////////// implementation of the routes ///////////////////////////////////
function send(req, res, next) {
var test = users.getAll();
res.json({ test: 'Hello ' + req.params.name });
return next();
};
My DB.js file looks the following:
var mysql = require('mysql'),
sync = require('async')
var PRODUCTION_DB = 'userDB',
TEST_DB = 'userDB'
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
mode: null,
}
exports.connect = function (mode, done) {
state.pool = mysql.createPool({
connectionLimit: 50,
host: 'localhost',
user: 'user',
password: 'password',
database: 'userDB' // test
//mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
})
state.mode = mode
done()
}
exports.get = function () {
return state.pool
}
Could it be, that the tutorial spared out an essential part in utilizing mysql pools and node.js?
Thanks in advance for at least trying to answer that question.
Are there better methods sequelize(?) available to create performant connections to a MySQL database?
It looks like creating the pool object does not actually connect to the database. A big clue is that the createPool function is not asynchronous, which is what you would expect if it was actually connecting at that moment.
You have to make use of the returned pool object to perform a query, which IS asynchronous.
From the documentation:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
I am new to Bookshelf JS and wanted to do a like query with the database. I read the documentation on their official website , but I am unable to figure this out.
The following is my code:
1. var DB = Bookshelf.initialize({
client: 'mysql',
connection: config
});
2. var User1=DB.Model.extend({
tableName: 'applicationPrimary',
});
3. Now I want to make a query like:
select * from applicationPrimary where id like '%2%' ;
4.I have tried the following:
Model.User1.query(function(qb) {
qb.where('id', 'LIKE', '%2%')
}).fetch()
.then(function(model) {
console.log(model)
});
The following is the manner I am initialising and setting up:
1. var Bookshelf = require('bookshelf');
var config = {
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydb',
charset: 'UTF8_GENERAL_CI'
};
var DB = Bookshelf.initialize({
client: 'mysql',
connection: config
});
module.exports.DB = DB;
2. var DB = require('./db').DB;
var User1 = DB.Model.extend({
tableName: 'applicationPrimary',
});
module.exports = {
User1: User1,
};
and then I am using it as:
var Model = require('./model');
in the file I am using User1.
The above doesn't work and it throws an error saying there is no function called query.
Any help is highly appreciated.
Your syntax for the LIKE is right, the problem is you should use .where on the User1 object, not .query on Model.User1
User1.where('id', 'LIKE', '%2%').fetch().then(...)
I'm studying Node.js + Express, coding a basic login example. My /login route is set inside the routes/login.js file:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
router.post('/', function(req,res){
connectionpool.getConnection(function(err, connection) {
if (err) {
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
} else {
// Do something
}
});
});
module.exports = router;
I was wondering: how can I make the mysql or the connectionpool visible in the entire application? I don't want to redeclare them on each route file I'll create. I'm looking something like an include or require method.
Any idea?
Create a separate module to act as an interface to retrieving SQL connections like so:
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
exports.getConnection = function (callback) {
connectionpool.getConnection(callback);
};
Then in another file:
var connections = require('./connections');
connections.getConnection(function (err, c) {
// Use c as a connection
c.query("select * from table limit 10 ",function(err,rows){
//this is important release part
c.release();
if(!err) {
console.log(rows);
}
});
});