In app.js, when express running, express will create pool connection. then pool instance can be access in other file. How to do that?
app.js
const express = require('express');
const app = express();
const port = 8080;
const mysql = require('mysql2');
const comic = require('./routes/comic');
app.use('/comics', comic);
app.listen(port, () => {
console.log(`Server is listening in ${port} port`);
const pool = mysql.createPool({
host:'localhost',
user: 'root',
password: 'test',
database: 'test'
});
exports.connection = pool.promise();
});
test.js
const {connection} = require('./app');
(async () => {
const [rows] = await connection.execute('SELECT * FROM people');
console.log(rows);
})();
I would recommend you to have a seperate db.js file that would have the connection pool and import that pool wherever necessary
In db.js
const mysql = require('mysql2');
const pool = mysql.createPool({
host:'localhost',
user: 'root',
password: 'test',
database: 'test'
});
module.exports = pool;
And in the place where u want it
let pool = require('./db');
const queryRes = (query, pool) => new Promise((resolve, reject) => {
pool.getConnection(function(err, connection) {
if(err) {
reject('Error');
}
connection.query(query, (err, results, fields) => {
if(err) {
reject('Error');
}
else{
connection.release();
resolve(results);
}
});
connection.on('error', (err) => {
reject('Error');
connection.release();
});
});
});
queryRes("Select * from test", pool).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
Related
var app = require('express')();
app.get('/', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'xxxxx',
server: 'xx',
database: 'formdangky',
port :'1443'
};
(async function () {
try {
let pool = sql.connect(config)
let result1 = await pool.request()
.query('select * from dondangky')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
res.send(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = 3000;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
When i trying code but then the result is empty end not show something
Node JS to SQL SERVER get null empty when i trying conect with mssql from Npm https://www.npmjs.com/package/mssql#asyncawait
to get reslut from database
I have been trying to connect to mongodb via my node app on a shared hosting cpanel but it only responds with error code 503 and logs "db.collection undefined" to the console, which means the connection was not successful.
This is the database connection in db.js:
const { MongoClient } = require('mongodb');
require('dotenv').config();
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect(`mongodb+srv://Achifa:${process.env.PASSWORD}#cluster0.exp9r.mongodb.net/?retryWrites=true&w=majority`)
.then((client) => {
dbConnection = client.db('newsDb')
return cb()
})
.catch(err => {
console.log(err)
return cb(err)
})
},
getDb: () => dbConnection
}
This is the app connection in app.js:
const {connectToDb, getDb} = require('./db');
let db;
var port = process.env.PORT || 50500;
connectToDb((err) => {
if(!err){
var server = app.listen(port, () => console.log("connected"));
db = getDb();
}
})
I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?
I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()
I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
const express = require('express')
const bodyParser = require('body-parser')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
const app = express()
app.use(bodyParser.json())
app.use(awsServerlessExpressMiddleware.eventContext())
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "*")
next()
});
// Connect to DB
const sql = require("mssql")
const config = {
server: "SERVER",
user: "USER",
password: "PASSWORD",
port: 1433,
database: "DATABASE"
}
console.log("Attemping to connect...")
let q = "SELECT * FROM QUERY"
// Async Await
async function getDB() {
console.log("Inside getDB...")
try {
let pool = await sql.connect(config)
console.log("Connected")
let item = await pool.request().query(q)
console.log(item)
sql.close()
return item;
} catch(err) {
console.log("Query did not complete.")
console.log(err.message);
sql.close();
}
}
let result = getDB();
console.log("Result: " + result)
app.get('/', function(req, res) {
res.status(200).json({result, url:req.url})
});
I am running an application using AWS amplify and I am trying to connect to an RDS database through my backend lambda function. When I check CloudWatch I get a failed connection to database. I'm not certain what the issue is because I use the exact same settings to connect using Python using the pyodbc library.
CloudWatch
var mysql = require('mysql')
var connection = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "snappay",
port : "3306"
})
connection.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
module.exports = connection
please follow this connection code hope it'll work
ref : https://github.com/vishalims095/nodeJS_Mysql/blob/developer/src/Modules/connection.js
index.js
const { Client } =require('pg');
const client = new Client ({
user: 'postgres',
host: 'localhost',
database: 'test',
password: 'admin',
port: 5432,
});
client.connect();
module.exports.myconnection = client;
app.js
const express = require("express");
const port = 3000;
const app =express();
const db =require("./db");
app.use(express.json());
const interactrouter = require("./routes/interactions");
app.use("/data",interactrouter);
app.listen(port, () =>
console.log(`Server running at http://localhost:${port}`) // not single cotaions above tab
);
interactions.js
const express = require ('express')
const router = express.Router()
const db =require('../db')
const { Client } = require('pg')
const client = new Client()
router.get('/',(req,res) => {
client.query("SELECT id, decription, drugcode, diseasecode, type FROM interactions;")
.then (rows =>{
console.log(rows);
res.json(rows)
})
.catch(error => {
console.log(error)
})
})
module.exports =router;
my problem I connect to the server but I can't get the data from the database and this is my code how can I fix it thank you all
so how can I fix it or what I should edit I'm new in this field