I'm completely new to nodejs + expressjs comming from php and I'm getting trouble how to export/include a var to my routes/users.js file.
on app.js I have:
//database connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});
... some code
var user = require('./routes/user'); //here I include my routes/files (I dont know if it's right to include the routes here - for learning purposes it works for now)
... more code until starts the server
On my /routes/user.js
app = require('../app');
//var mysql = require('mysql');
var baseUrl = app.get('baseUrl');
app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});
and I get the express error: 500 ReferenceError: connection is not defined
The connection works because if I move the content from users.js to app.js I can query the database.
My questions is how to inject the var connection to be used on routes/users.js
Any help / hint to understand this is very appreciated. Thanks in advance.
There are several ways you could do this. A couple solutions might be:
Create a resources.js file that creates and exports the connection. Then require() resources.js in every source file where you need it.
Pass the connection to your user route file. Something like this:
// app.js
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});
require('./routes/user')(connection);
// routes/user.js
module.exports = function(connection) {
app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});
};
create a database connector javascript file. as like database_connector.js
and require it when ever you want to have the connection pooled or the connection class availabel to your models. tip : you can also export config files like below or use barely values.
var mysql = require('mysql');
var config = require("./config");
function Connection() {
this.pool = null;
this.init = function() {
this.pool = mysql.createPool({
connectionLimit: config.poolSize,
host: config.host,
user: config.user,
password: config.password,
database: config.database,
debug:config.debug,
});
};
this.acquire = function(callback) {
this.pool.getConnection(function(err, connection) {
callback(err, connection);
});
};
console.log("connection"+this.pool);
}
module.exports = new Connection();
Related
I have a nodejs code like this
const mysql = require('mysql');
const express = require('express');
const app = express();
class ConnectDatabase{
constructor(){
this.connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
});
};
getVersion() {
this.connection.query('SELECT * FROM version', function (err, results) {
return results[0].version // if use console.log() i get my data
});
};
};
var APP = new ConnectDatabase()
console.log(APP.getVersion());
when i use console.log(results[0].version), i get my data, but when i use return my data becomes undefined
I am Node js Developer i am using mongodb. i think everything fine.
3 possible problem
1 first check xampp is running
2 connection build with database or not
3 table name
I am creating a application that will communicate over Udp protocol in node js. Also i am using sql server as a database so in order to connect this database i am using mssql npm liabrary. Basically what i am doing i have one separate module for dbcon as shown below
const sql = require('mssql')
const config = {
user: 'sa',
password: '123',
server: '192.168.1.164', // You can use 'localhost\\instance' to connect to named instance
database: 'SBM-EMCURE',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
sql.connect(config, err => {
})
sql.on('error', err => {
console.log('error on sql.on()');
})
module.exports.sql = sql;
And i am using this exported sql object to run my queries outside dbcon module but it gives me different behavior sometimes like query executes before databse connection, is there is any way to use single database connection for entire application?. Using single database connection is useful or it will slow down my process
Thanks in advance
You could:
Pass the instance into each router and use it there when you set them up
Set the instance as a property of your app object and access it from req.app.sql or res.app.sql within your middleware functions
Set the instance as a property of the global object and access it from anywhere (typically not a best practice though)
Also, in your example code, you're initiating the connection by calling sql.connect(), but you don't give it a callback for when it's finished connecting. This is causing it to be immediately exported and probably queried before the connection is actually established. Do this:
const util = require('util');
const sql = require('mssql');
const config = {
user: 'sa',
password: '123',
server: '192.168.1.164',
database: 'SBM-EMCURE',
options: {
encrypt: false
}
};
module.exports = util.promisify(sql.connect)(config);
Then you can retrieve the instance with:
const sql = await require('./database.js');
first you should create file database.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'event'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Then you can use this connection in server.js or any other file.
var express = require('express');
var app = express();
var dbcon = require('./database');
app.get('/getEvent',function(req,res){
dbcon.query('SELECT * FROM eventinfo',function(err, result) {
if (err) throw err;
});
});
app.listen(3000);
What does createConnection do?
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
I'm writing an application in nodeJS using mysql module. I have some own modules, for example authentication, which definetely needs DB connection. Question is: if I have multiple modules where I use this method to create the connection, will it create a new connection for me everytime or use the first one? If creates, it creates the first time it loads my own module or everytime? Oh, and if it creates when is it going to be destroyed?
Here's how I have it in my authentication module:
var config = require('./config.js');
var mysql = require('mysql');
var connection = mysql.createConnection(config.connectionString);
exports.login = function() ...
I have some basic understanding missings about how modules and own modules work.
Thanks for the answers.
You can create a connection pool in one module and then share that pool across all your modules, calling pool.getConnection() whenever you need to. That might be better than keeping a single, shared connection open all the time.
One project I'm working on does this:
utils/database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'xxxxx',
password: 'yyyyy',
database: 'zzzzz',
debug: false
});
module.exports = pool
accounts.js
var express = require('express');
var router = express.Router();
var pool = require('./utils/database');
router.get('/', function(req, res) {
pool.getConnection(function(err, connection) {
// do whatever you want with your connection here
connection.release();
});
});
module.exports = router;
Another way I'm playing around with is like this:
utils/database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'xxxxx',
password: 'yyyyy',
database: 'zzzzz',
debug: false
});
var getConnection = function(callback) {
pool.getConnection(function(err, connection) {
callback(err, connection);
});
});
module.exports = getConnection;
accounts.js
var express = require('express');
var router = express.Router();
var createConnection = require('./utils/database');
router.get('/', function(req, res) {
createConnection(function(err, connection) {
// do whatever you want with your connection here
connection.release();
});
});
module.exports = router;
It will create a new connection every time you call connection.connect().
The connection is destroyed when either the program exits, or connection.end() is called. If you want to reuse the connection, you can put the connection logic in a separate module and then just export the connection itself, like this.
In a file called connection.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'password'
});
connection.connect();
module.exports = connection;
And then in any client file:
var connection = require("./connection.js");
connection.query('some query', callback);
Each file the requires connection.js will reuse the existing connection.
I'm using a networking website in node using express and postgresql - using the pg npm module - as my database.
I'm now trying to setup user pages like this:
...
app.get('/u/:u/', function (req, res) {
pool.connect(function(err, client, done) {
...
client.query('SELECT * FROM users WHERE id =($1)', [req.params.u], function(err, result) {
... done(); ...
});
});
});
...
req.params.u returns undefined inside the DB query.
I assume it's because the call back function isn't in the same scope as the app route, how do I get about checking the database like this?
I have a feeling there's a much better way of doing this.
So if the problem is that params gets undefined, the solution should come from something similar to:
...
app.get('/u/:u/', function (req, res) {
var tempReq = req
pool.connect(function(err, client, done) {
...
client.query('SELECT * FROM users WHERE id =($1)',[tempReq.params.u], function(err, result) {
... done(); ...
});
});
});
...
Make sure to put your body-parser code above all the routes in your app.js file to get req.body or req.params or req.query value
var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
And your req object is available in your whole route's scope then you can use it in any where in this block no need to store in local variable
app.get('/u/:u/', function (req, res) {
pool.connect(function(err, client, done) {
...
client.query('SELECT * FROM users WHERE id =($1)',[req.params.u], function(err, result) {
... done(); ...
});
});
});
You can communicate with more than one database at a time too
You need ssl first..
var fs = require('fs');
var SSLkey = fs.readFileSync('/local/pem/location/key.pem');
var SSLcert = fs.readFileSync('/local/pem/location/cert.pem');
Now the database code
const mysql = require('mysql');
const forumdb_db = mysql.createConnection({
host: 'localhost',
user: 'dbuser',
password: 'dbpassword',
database: 'dbname',
key: SSLkey,
cert: SSLcert,
connectionLimit: 15,
queueLimit: 30,
acquireTimeout: 1000
});
const inventory_db = mysql.createConnection({
host: 'localhost',
user: 'dbuser',
password: 'dbpassword',
database: 'dbname',
key: SSLkey,
cert: SSLcert,
connectionLimit: 15,
queueLimit: 30,
acquireTimeout: 1000
});
Connecting to databases
inventory_db.connect((err0) => {
inventory_db.query("SELECT `bubblebum` FROM `user_inventory` WHERE `index`='1' LIMIT 1;", function(err0, result0, field0) {
console.log(result0[0].bubblebum);
});
});
forum_db.connect((err0) => {
forum_db.query("SELECT `stars` FROM `user_inventory` WHERE `stars`>'100' LIMIT 1;", function(err1, result1, field1) {
console.log(result1[0].stars);
});
});
There is one problem with this, You'll be disconnected after a while of inactivity so you should set up an interval to send a quick request every ten seconds to the sql server.
I'm using Express.js and MongoLab and I followed the Heroku setup to get MongoDB working in production throwing this code in my app.js.
//Mongo on Heroku Setup
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('mydocs', function(er, collection) {
collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
});
});
});
and I have the following routes and field for my email form (also in app.js):
//Routes
app.get('/', function(req, res) {
res.render('index', {
title: 'DumbyApp'
});
});
//save new email
app.post('/', function(req, res){
emailProvider.save({
address: req.param('address')
}, function( error, docs) {
res.redirect('/')
});
});
This renders the new form on the index page and lets me save it locally but not in production because I don't know how to setup my email collection. Can anyone walk me through this? brand new to using MongoDB and Node.js, so could use some help.
EDIT:
In The MongoLab Database Interface, I made a collection called emails. Is this the right course of action?
EDIT 2:
Here's defining EmailProvider in app.js along with the file itself.
app.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, EmailProvider = require('./emailprovider').EmailProvider;
var emailProvider= new EmailProvider('localhost', 27017);
emailprovider.js
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmailProvider = function(host, port) {
this.db= new Db('localdb', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
EmailProvider.prototype.getCollection= function(callback) {
this.db.collection('emails', function(error, email_collection) {
if( error ) callback(error);
else callback(null, email_collection);
});
};
//save new email
EmailProvider.prototype.save = function(emails, callback) {
this.getCollection(function(error, email_collection) {
if( error ) callback(error)
else {
if( typeof(emails.address)=="undefined")
emails = [emails];
for( var i =0;i< emails.address;i++ ) {
email = emails[i];
email.created_at = new Date();
}
email_collection.insert(emails, function() {
callback(null, emails);
});
}
});
};
exports.EmailProvider = EmailProvider;
While the connection code in the first code box appears to be correct, the emailProvider object isn't using it. Instead, in app.js, the EmailProvider is being connected to localhost:27017 and the database name is hardcoded in emailprovider.js as 'localdb'.
What you want to do instead is use the connection information provided in the MONGOLAB_URI environment variable in your EmailProvider, which contains the host, port, and database name already.
There are a number of ways to go about doing this, but one way would be to move your connection code from that first code box into the EmailProvider constructor, and then change the constructor so that it takes a URI instead of a host and port. That way, you can pass the MONGOLAB_URI variable to the constructor in app.js.