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);
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 try to connect to postgreSQL database and display the results in my html file.
I use node-postgres module version ^7.7.1
My code is:
const express = require('express');
const { Pool, Client } = require('pg');
const pg = require('pg');
const config = {
user: 'username',
database: 'db_name',
password: 'userpass',
port: 3000
};
app.get('/', function (req, res) {
const pool = new pg.Pool(config)
const client = new pg.Client(connect);
// connection using created pool
pool.connect(function(err, client, done) {
client.query('SELECT * FROM example_table')
res.render('index')
done()
})
pool.end()
});
I'm getting error: Cannot read property 'query' of undefined.
What's the proper way to connect to database and render the result ?
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 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();
I am having trouble making node.js and mongodb with mongolab work on heroku. I have read other issues like How do I setup MongoDB database on Heroku with MongoLab? and How do I manage MongoDB connections in a Node.js web application? but I still can not set up my connection. In the logs it says [Error: failed to connect to ...]
I have takend the db, host and port from the MONGOLAB_URI process env.I have the following code:
var mongoUri = mongodb://heroku_app17328644:{password}#ds037518.mongolab.com //taken from process.env.MONGOLAB_URI
var host = 'mongodb://heroku_appXXXXXX:{password}#ds037518.mongolab.com';
var port = '37518';
var database = 'heroku_appXXXXXX';
Provider.db = new Db(database, new Server(host, port, { safe: true }, { auto_reconnect: true }, {}));
Provider.db.open(function(err, db){
console.log(db); //null
if (err) console.log(err);
else console.log('success');
});
What am I doing wrong ?
The core issue seems to be that you're trying to use a MongoDB URI as a hostname.
Here's how to connect using a URI and MongoClient:
var mongodb = require('mongodb');
var uri = 'mongodb://user:pass#host:port/db';
mongodb.MongoClient.connect(uri, function (err, db) {
/* adventure! */
});
Of course you'll want to substitute the user, pass, host, port, and db in the uri for your actual connect parameters. If you're using the MongoLab add-on for Heroku you can get the URI from the environment like this:
var uri = process.env.MONGOLAB_URI;
When using MongoClient safe mode is the default, so that option can be left out. To specify auto_reconnect simply pass it as a server option.
var mongodb = require('mongodb');
var uri = 'mongodb://user:pass#host:port/db';
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, db) {
/* adventure! */
});
Here's is how I do it. This way, my application connects to the "test" database on my development machine and the "mongolab" database when deployed and running on Heroku.
mongoose = require("mongoose");
mongoURI = 'mongodb://localhost/test';
mongoose.connect(process.env.MONGOLAB_URI || mongoURI);
In my own case, I queried the configuration settings heroku config and it turns out that the mongodb is added as MONGODB_URI.
So, I added process.env.MONGODB_URI to the uri such as:
var uri = process.env.MONGODB_URI || process.env.MONGOHQ_URL || process.env.MONGOLAB_URI;