Require connection mysql in Express 4 for MVC structure - node.js

I'm using express with node-mysql to implement an MVC app. I want to ask the best way to get connection of mysql in each models file.
My models file is in directory models.
In app.js of express, I create a connection like :
var db = mysql.createConnection({
host: config.dbHost,
user: config.dbUser,
password: config.dbPassword,
database: dbName
});
I can use :
app.use(function(req,res,next){
req.db = db;
next();
});
then in modules,models get connection by call req.db.query().. but I think it's not good for performance.
What should I do ?
Edit:
if I have to access different database in each request, meaning create many connections. What 's the best way to do it ?

Related

TypeORM connection without explicitly specifying database

I wonder if it is somehow possible using TypeOrm to connect to a database server without having to specify a schema.
With the normal mysql module in Node it would work like this:
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password:"xxx"
});
However, a database must be specified in the connection options in TypeOrm, if this is an empty string or does not exist, an error occurs.
So I don't see any possibility to connect to the server with TypeOrm and create a new schema with this connection.
Do I have to use the normal mysql module or is there a possibility with TypeORM that I am not aware of?

How to create a pool object in javascript that can connect to a database backend using SSL?

I followed a guide on how to create a Node JS backend on PostgreSQL and a ReactJS frontend, which is working well, see here for more.
The js pool object of the quide looks as follows:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'my_user',
host: 'localhost',
database: 'my_database',
password: 'postgres',
port: 5432,
});
I tried doing the same with a PostgreSQL Webserver using SSL encryption. This question is not tagged postgresql since the pool looks the same for mysql and other databases. It is also not tagged Linux since it should work the same on other OS.
How to create a pool object from the Pool class in javascript that can connect to a PostgreSQL backend using SSL?
You need to save the certificate, call it server-certificate.pem, in a place with a static path starting with / (~ for your user's home directory does not work). Therefore, you need to move it to a static place.
I copied the file to a newly created directory certificates, but that is of course up to you. You will need super user rights for this.
/etc/certificates/server-certificate.pem
You need to load fs and use it in the SSL part, see How to establish a secure connection (SSL) from a Node.js API to an AWS RDS.
const Pool = require('pg').Pool
const fs = require('fs');
const pool = new Pool({
user: 'my_user',
host: 'my_host',
database: 'my_database',
password: 'my_password',
port: 22222,
ssl: {
ca: fs
.readFileSync("/etc/certificates/server-certificate.pem")
.toString()
}
});

How to Get Data From DB with angular

I have a front-end website created as Angular project. (using node.js) I have created a "server.ts" file and connected to the my DB succesfully. Now I want to get data from my database and print some on dashboard. How can I get data ?
var mysql = require('mysql');
var con = mysql.createConnection({
host: "myhost",
user: "myusername",
password: "mypassword"
});
con.connect(function(err){
if (err) throw err;
console.log("Connected!");
});
You can't get data from the database in an Angular app. Angular is a front-end framework, it means that you angular application will be downloaded and executed in the user's browser.
To access data from the database that is in the server side, you need a back-end application. You could do it from a node.js application with help of a framework like mysqljs.
There is an example in this video
You will need to create some sort of api for your front-end application to communicate with the backend server. A common option for this is Express. This involves quite a lot of code, so if you want specific help I suggest putting together a stackblitz, alternatively you may be interested in the following example:
https://morioh.com/p/33d0377536a6/angular7-crud-with-nodejs-and-mysql-example
If you want a more complete solution, you could also look into implementing a tooling system such as Prisma
from lib README on Github:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
you can use .query() for example to trigger requests and fetch data.

How do I correctly authenticate in mongo for a user that has access to multiple databases?

I have a user with the role: {role: 'root', db:'admin'} which should have access to all the databases in my mongo instance. I'm using mongoskin in node.js to interact with mongo. My problem is that it isn't correctly accessing my databases. If I authenticate with
mongodb://owner:mylocalpassword#localhost:27017/mydatabase
It simply gives me MongoError: Authentication failed. If I instead auth with:
mongodb://owner:mylocalpassword#localhost:27017/admin
it authenticates, but I can't access mydatabase.
Here's my connection code:
var connection = mongoskin.db("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal:true, auto_reconnect:true})
I assume that since I'm accessing the admin database there, that's the only one it interacts with. So I tried do then do this:
var mydatabaseConnection = connection.db('mydatabase')
But when I use that, my app is returning no results for queries on collections that I know have data. What am I doing wrong here? How do I get this user to access a database other than admin?
Ok, so I found out that mongoskin's db method simply doesn't work. Finally I'm forced to completely remove mongoskin from my codebase. The real answer here is don't use mongoskin.
This code worked with mongo native:
MongoClient.connect("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal: true, auto_reconnect:true}).then(function(db) {
console.log("Connected!")
var mydb = db.db('mydatabase')
var User = mydb.collection('User')
return User.find({}).toArray().then(function(users) {
console.log(users)
db.close()
})
}).catch(function(e) {
console.log(e.stack)
})

Referencing NodeJS MongoDB connection from AngularJS

I'm trying to set up a small development environment consisting of a node.js http server, a mongodb database and frontend in angular.js. For development purposes I've created an account with MongoHQ and can reference my db using a URL.
The issue I'm faced with is that I can easily connect to my db from my Angular code but then my connection info is exposed through my http server.
So what I would like to be able to is to create my connection in my NodeJS server.js file and reference it from eg. my AngularJS app.js file. Is that possible and if so how?
Thanks in advance
Try using express and mongoose.
Server side code
var express = require('express');
var app = express();
//start server with port of choice here
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Foo=mongoose.model('foo');
//foo is a model. Check mongoose documentation from collections and schemas
app.get('/hello', function(req, res){
//get data from mongo using mongoose
foo.find({},function(err,docs){
//do stuff here
res.send(docs)
})
});
Front end code
$http.get('/hello').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
//data is the data from mongodb
})
Follow this tutorial to get an idea
There is a stack called MEAN Stack. See if it fits your needs. Very easy to set up and develop.

Resources