How to Get Data From DB with angular - node.js

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.

Related

Issue when I use require in electron

I'm doing a simple newsletter app in electron, I need to connect to my database, but if I use "require" to call mysql library it gives me "require is not defined", I tryed to use browsify but it didn't work, somebody can help me? (This script is in an HTML page)
<script>
document.getElementById("btn").addEventListener("click", () => {
var mysql = require (['./node_modules/mysql']);
var connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'db',
});
$sql = 'SELECT `id`,`first_name`,`last_name`,`email` FROM `subscribers`';
connection.query($sql, function (error, results, fields) {
if (error) throw error;
console.log(results);
$('#resultDiv').text(results[0].email);
});
connection.end();
})
</script>
Require is not part of the standard JS API, it is part of the Node API. There is a great writeup here. The renderer process in electron, where the HTML is rendered, does not have access to the node API directly. You can setup a framework like Angular or React which gives you more more robust development environment, or you can use the Node API in the main process to fetch the data for you. You can send information back and forth using IPC calls to allow the HTML page to signal to the main process that information is needed. The docs here do a good job showing how this is done.
I think you'd be more successful however using a web development framework rather than using IPC calls for this purpose.

Mongodb Monk reauthentication on connection

I have a node program connecting to a MongoDB. Theres a production server where we do proper authentication to connect to the db, but during development on our local machines it's just more tedious to keep track of authentication, especially because most of the time we completely wipe the db often. So resetting up authentication becomes even more tedious. So my solution was to attempt to connect to the db securely, and then if it fails then try to connect to the db in the dev fashion. Heres the code:
var db = require('monk')('username:password#localhost/TESTR', {authSource:'admin'});
db.catch(function(err) {
clog.i("MONGO AUTHENTICATION FAILED, USING NO AUTH CLIENT");
db = require('monk')('localhost/TESTR')
});
The problem is that this doesn't work. The rest of the app just complains about the authentication failure the first attempt had. Is there a better solution to this? Or am I just a moron?
var monk = require('monk');//layer used to connect mongodb
var db = monk('*****:27017/TESTR');
var collection = db.get('collection_name');
//you can access your collection using the mongo query
//simple controller action
module.exports = function(req, res){
collection.find({}, function(err, cb){
if(err) {res.json("db exception");}
else{res.json(cb)//it returns the db collections}
};
}

how are server side script safe and hidden which are written with Node js?

First check this code which is written in node js and has used sql module on it.
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(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Above code have some private information like database name,user,password and sql query too.I am not new at node.js but not that expert on it.If a script which have been written on Node.js will save in .js format and what if it contain server side script too?I mean how can it be safe/hidden like .php do?
Server side codes (NodeJS, PHP etc) are executed on your server and only the output of the executed code is sent to the browser or client.
Incase of NodeJS script above, it is executed on your node server. However, with the NodeJS you will need to make sure that those directories (your source code) are not served as static contents.

Require connection mysql in Express 4 for MVC structure

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 ?

Connection to Mongodb-Native-Driver in express.js

I am using mongodb-native-driver in express.js app. I have around 6 collections in the database, so I have created 6 js files with each having a collection as a javascript object (e.g function collection(){}) and the prototypes functions handling all the manipulation on those collections. I thought this would be a good architecture.
But the problem I am having is how to connect to the database? Should I create a connection in each of this files and use them? I think that would be an overkill as the connect in mongodb-native-driver creates a pool of connections and having several of them would not be justified.
So how do I create a single connection pool and use it in all the collections.js files? I want to have the connection like its implemented in mongoose. Let me know if any of my thought process in architecture of the app is wrong.
Using Mongoose would solve these problems, but I have read in several places thats it slower than native-driver and also I would prefer a schema-less models.
Edit: I created a module out of models. Each collection was in a file and it took the database as an argument. Now in the index.js file I called the database connection and kept a variable db after I got the database from the connection. (I used the auto-reconnect feature to make sure that the connection wasn't lost). In the same index.js file I exported each of the collections like this
exports.model1 = require('./model1').(db)
exprorts.model2 = require('./model2').(db)
This ensured that the database part was handled in just one module and the app would just call function that each model.js file exported like save(), fincdbyid() etc (whatever you do in the function is upto you to implement).
how to connect to the database?
In order to connect using the MongoDB native driver you need to do something like the following:
var util = require('util');
var mongodb = require('mongodb');
var client = mongodb.MongoClient;
var auth = {
user: 'username',
pass: 'password',
host: 'hostname',
port: 1337,
name: 'databaseName'
};
var uri = util.format('mongodb://%s:%s#%s:%d/%s',
auth.user, auth.pass, auth.host, auth.port, auth.name);
/** Connect to the Mongo database at the URI using the client */
client.connect(uri, { auto_reconnect: true }, function (err, database) {
if (err) throw err;
else if (!database) console.log('Unknown error connecting to database');
else {
console.log('Connected to MongoDB database server at:');
console.log('\n\t%s\n', uri);
// Create or access collections, etc here using the database object
}
});
A basic connection is setup like this. This is all I can give you going on just the basic description of what you want. Post up some code you've got so far to get more specific help.
Should I create a connection in each of this files and use them?
No.
So how do I create a single connection pool and use it in all the collections.js files?
You can create a single file with code like the above, lets call it dbmanager.js connecting to the database. Export functions like createUser, deleteUser, etc. which operate on your database, then export functionality like so:
module.exports = {
createUser: function () { ; },
deleteUser: function () { ; }
};
which you could then require from another file like so:
var dbman = require('./dbmanager');
dbman.createUser(userData); // using connection established in `dbmanager.js`
EDIT: Because we're dealing with JavaScript and a single thread, the native driver indeed automatically handles connection pooling for you. You can look for this in the StackOverflow links below for more confirmation of this. The OP does state this in the question as well. This means that client.connect should be called only once by an instance of your server. After the database object is successfully retrieved from a call to client.connect, that database object should be reused throughout the entire instance of your app. This is easily accomplished by using the module pattern that Node.JS provides.
My suggestion is to create a module or set of modules which serves as a single point of contact for interacting with the database. In my apps I usually have a single module which depends on the native driver, calling require('mongodb'). All other modules in my app will not directly access the database, but instead all manipulations must be coordinated by this database module.
This encapsulates all of the code dealing with the native driver into a single module or set of modules. The OP seems to think there is a problem with the simple code example I've posted, describing a problem with a "single large closure" in my example. This is all pretty basic stuff, so I'm adding clarification as to the basic architecture at work here, but I still do not feel the need to change any code.
The OP also seems to think that multiple connections could possibly be made here. This is not possible with this setup. If you created a module like I suggest above then the first time require('./dbmanager') is called it will execute the code in the file dbmanager.js and return the module.exports object. The exports object is cached and is also returned on each subsequent call to require('./dbmanager'), however, the code in dbmanager.js will only be executed the first require.
If you don't want to create a module like this then the other option would be to export only the database passed to the callback for client.connect and use it directly in different places throughout your app. I recommend against this however, regardless of the OPs concerns.
Similar, possibly duplicate Stackoverflow questions, among others:
How to manage mongodb connections in nodejs webapp
Node.JS and MongoDB, reusing the DB object
Node.JS - What is the right way to deal with MongoDB connections
As accepted answer says - you should create only one connection for all incoming requests and reuse it, but answer is missing solution, that will create and cache connection. I wrote express middleware to achieve this - express-mongo-db. At first sight this task is trivial, and most people use this kind of code:
var db;
function createConnection(req, res, next) {
if (db) { req.db = db; next(); }
client.connect(uri, { auto_reconnect: true }, function (err, database) {
req.db = db = databse;
next();
});
}
app.use(createConnection);
But this code lead you to connection-leak, when multiple request arrives at the same time, and db is undefined. express-mongo-db solving this by holding incoming clients and calling connect only once, when module is required (not when first request arrives).
Hope you find it useful.
I just thought I would add in my own method of MongoDB connection for others interested or having problems with different methods
This method assumes you don't need authentication(I use this on localhost)
Authentication is still easy to implement
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var client = new MongoClient(new Server('localhost',27017,{
socketOptions: {connectTimeoutMS: 500},
poolSize:5,
auto_reconnect:true
}, {
numberOfRetries:3,
retryMilliseconds: 500
}));
client.open(function(err, client) {
if(err) {
console.log("Connection Failed Via Client Object.");
} else {
var db = client.db("theDbName");
if(db) {
console.log("Connected Via Client Object . . .");
db.logout(function(err,result) {
if(!err) {
console.log("Logged out successfully");
}
client.close();
console.log("Connection closed");
});
}
}
});
Credit goes to Brad Davley which goes over this method in his book (page 231-232)

Resources