how are you doing? Does anyone know how to create database connection dynamically using NodeJS, Express, and Sequelize?
My development team is developing an API for our mobile application, and on the login page, we'll have 3 fields:
Enterprise Code
Username
Password
When the user inputs the "Enterprise Code", I need to go to my default database, which stores all our customers and search the client data based on what was inputted in the field. Let's suppose that the enterprise code is 147, then the API goes to the customer's table into the default database and search for the data where customer_id = 147. That will return the customer data, which also contains its database name, for example, 147_enterprisename, which is a database named "147_enterprisename" referring to this customer.
What I need is: Create a Sequelize connection based on which "Enterprise Code" was typed, like this:
const Sequelize = require('sequelize')
const sequelize = new Sequelize(dynamic_database_name, 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
})
I also need that the API returns the connection to all routes, where is the functions that fetch data from the database and so on.
Related
I'm very new to databases and mysql, but i have to know how i update my database from a pre-written javascript query. Until now i have done it manually over the terminal in javascript with: node main.js. This works just fine but i want to do this with a button.
const { createPool } = require('mysql')
const pool = createPool({
host: 'localhost',
user: 'root',
password: '',
connectionLimit: 10,
})
pool.query(`
insert into test.users(first_name, last_name, email)
values('${fname.value}', '${lname.value}', '${email.value}')
`)
Thank you in advance.
I could not try very much because i didn't find much and all the tutorials i watched on youtube were not helpful at all.
Recently I have a requirement to be able to implement a MeteorJS application capable of connecting to different databases according to the connected user.
The structure of the database is the same, only the information it contains changes
I tried connecting through DDP to another backend connected to the necessary database and also by using MongoInternals but, although the users log in correctly, the other collections continue to consult the database by default.
In the server code
const connection = DDP.connect(url)
Accounts.connection = Meteor.connection = connection
_.each(
[
"subscribe",
"methods",
"call",
"apply",
"status",
"reconnect",
"disconnect",
],
function (name) {
Meteor[name] = _.bind(Meteor.connection[name], Meteor.connection); // 55
}
);
ConfigApps = new Mongo.Collection("configapps")
Here the ConfigApps collection obtains the correct data from the database but from the Frontend the data from the other database is read
Or:
var database = new MongoInternals.RemoteCollectionDriver(
"mongodb://localhost:27017/spence-local"
);
ConfigApps = new Mongo.Collection("configapps", {
_driver: database,
_suppressSameNameError: true,
});
Meteor.users = new Mongo.Collection("users", {
_driver: database,
_suppressSameNameError: true,
});
With the same results. User can connect but only one database is read for all querys in the application
Some information or clue would be great.
I have a weird behavior while I'm trying to query my MySQL database from a nodeJS API.
I define a connection pool to mysql on node using the following code
const mysql = require('mysql2')
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: 'mydb.user',
database: process.env.DB_DB,
password: process.env.DB_PWD,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
multipleStatements: true
}).promise()
Before that, I was using another user named mydb.owner defined in a .env file.
When I execute a query, I have the following error
Access denied for user 'mydb.owner'#'localhost' to database 'mydb'
That's not the user I've configured, that's the old one.
If I have a look on the Mysql connections, I can see that the user of the pool is correct:
show processlist;
Returns
Id User Host db
6 root localhost:37752 mydb
9 mydb.user localhost:38102 mydb
It seems I haven't any environment variable defined from elsewhere:
echo $DB_USER
Returns nothing.
The user seems to have the necessary rights :
SHOW GRANTS FOR 'mydb.user'#'localhost';
GRANT USAGE ON *.* TO 'mydb.user'#'localhost'
GRANT SELECT, INSERT, UPDATE, DELETE, EXECUTE ON `mydb`.* TO 'mydb.user'#'localhost' WITH GRANT OPTION
I don't understand why mysql2 returns me an error about my old user mydb.owner.
The query was a stored procedure and was created by default with the tag
CREATE definer = 'mydb.owner'#'localhost' PROCEDURE ...
No matter which user execute the stored procedure, it was impersonated with the mydb.owner account.
To specify that the procedure must be executed under the current account, I added the following instructions:
CREATE definer = 'mydb.owner'#'localhost' PROCEDURE ...()
SQL SECURITY INVOKER
BEGIN ...
i have searched lot to get a solution to my problem. but didn't got it.
if anyone have the experience in such situations please help me.
i have created a application server in node express with MySQL a database.
and successfully create REST API endpoints which works successfully.
but our projects scaled up. a new client approaches so we need to serve those clients too.
those client may have 1k users.but the database schema is same.
solution 1: create a separate server and database for each client with different port no.
but i don't think this is good solution because if we have 100 client we can't maintain the code base.
solution 2: create a separate database for each client and switch database connection at run time.
but i don't understand how to implement solution 2. any suggestion highly appreciated.
if more than one client requesting same server how to know which database need to connect using the endpoint URL. i there any alternate way to tackle this situation.
my solution: create a middle ware to find out the which database is required and return the connection string.is it good idea.
middleware. in below example i use JWT token which contain database name.
const dbHelper=new db();
class DbChooser {
constructor(){
this. db=
{
wesa:{
host: "xxx",
user: "xxxx",
password: "xxxxx",
database: "hdgh",
connectionLimit:10,
connectTimeout:30000,
multipleStatements:true,
charset:"utf8mb4"
},
svn:{
host: "x.x.x.x.",
user: "xxxx",
password: "xxx",
database: "xxx",
connectionLimit:10,
connectTimeout:30000,
multipleStatements:true,
charset:"utf8mb4"
}
};
}
async getConnectiontring(req,res,next){
//console.log(req.decoded);
let d=new DbChooser();
let con=d.db[req.decoded.userId];
console.log(mysql.createPool(con));
next();
}
}
module.exports=DbChooser;
You can create a config JSON. On every request, request header should have a client_id based on the client_id we can get the instance of the database connection.
your db config JSON
var dbconfig = {
'client1': {
databasename: '',
host: '',
password: '',
username: ''
},
'client2': {
databasename: '',
host: '',
password: '',
username: ''
}
}
You should declare a global object, to maintain the singleton db instances for every client.
global.dbinstances = {};
on every request, you are going to check whether the instance is already available in your global object or not. If it's available you can go continue to the next process, otherwise it creates a new instance.
app.use('*', function(req,res) {
let client_id = req.headers.client_id;
if(global.instance[client_id]) {
next();
} else {
const config = dbconfig[client_id];
connectoDb(config, client_id);
}
}
function connectoDb(config, client_id) {
//.. once it is connected
global.instance.push({client_id: con}); //con refers to the db connection instance.
}
I am trying to connect to SQL Server 2014 with NodeJS, i am using the "mssql" package, i dont have answer here is my code
var sql = require('mssql');
var opciones = {
user: 'myuser',
password: 'mypass',
server: 'myserver',
database: 'mydatabase',
options: {
encrypt: true
}
};
sql.connect(opciones,function(err){
if(err){
console.log(err);
}else{
console.log("CONEXIÓN EXITOSA");
}
});
the name of that js is "cnSQL.js", when i execute on cmd "node cnSQL" I dont have answer.
Tested the code as above with my local DB instance.
The code is actually correct.
var sql = require('mssql');
var opciones = {
user: 'sa',
password: 'mypass',
server: '127.0.0.1',
database: 'mydb',
options: {
encrypt: true
}
};
sql.connect(opciones,function(err){
if(err){
console.log(err);
}else{
console.log("CONEXIÓN EXITOSA");
}
});
I have managed to get the 'Connexion Exitosa' message.
In order to further debug your issue, attempt the following:
With the username you are trying to login with (In my case 'sa')
Open SQL Server Management Studio and attempt to put in the connection information as above. Click login, does that work?
If not:
Open SQL Server Management Studio
Connect to the SQL Server Instance you are trying to connect to from NodeJS
Right click on the instance of your SQL server and click properties
Click security and ensure that the "SQL Server and Windows Authentication mode" radio button is selected.
When done click OK
On the left hand navigation expand the Node "Security"
Expand Logins
Find your user and ensure it is enabled and that the password you selected reflects the password within your NodeJS app.
If so:
Amend all the information within the code to reflect exactly the credentials used to login
Special Note: '.' will not represent localhost here. Use 127.0.0.1 or localhost
Furthermore, if the SQL server instance you are trying to connect to is not hosted locally. Ensure that the machine it is hosted on accepts connections on port 1433 (by default for SQL Server).
Hope it helps!