Connect to postgreSQL and render using node.js - node.js

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 ?

Related

Nodejs class return undefined

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

Make post request to Mongodb Atlas using Nodejs

I was familiar with MongodB for CRUD operation. Here, I'm trying to make simple post request on mongodB atlas but I want to know where I have done error for the connection and posting data to MongodB atlas.
Model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let quizSchema = new Schema({
title: {
type: String,
},
description: {
type: Number,
},
question: {
type: String,
},
});
const Quiz = mongoose.model("Quiz", quizSchema);
module.exports = Quiz;
index.js
I'm trying to create the database collection name "QuizDatabase" and insert the data to it.
var express = require("express");
var bodyParser = require("body-parser");
const Quiz = require("./views/model/model");
var Request = require("request");
var app = express();
app.use(bodyParser.json());
const MongoClient = require("mongodb").MongoClient;
const uri =
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connect(uri);
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/new/", function (req, res) {
Quiz.collection("QuizDatabase").insertMany(req.body, function (err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new quiz.");
} else {
res.status(201).send(JSON.stringify(body));
}
});
});
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ error: message });
}
You dont have to use mongo client if you are already using mongoose.
In index.js file just import the model
const Quiz = require("./model");
And you are already using mongoose to connect to db when you write mongoose.connect(uri); You don't have to use client.connect() again.
Query to insert -
Quiz.insertMany(req.body);
Your index file should look like this -
const Quiz = require("./views/model/model");
var Request = require("request");
var app = express();
app.use(bodyParser.json());
const uri =
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
mongoose.connect(uri);
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/new/", function (req, res) {
Quiz.insertMany(req.body, function (err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new quiz.");
} else {
res.status(201).send(JSON.stringify(body));
}
});
});
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ error: message });
}
There are several reasons.
Connection Issues to the MongoDB database.
To check this insert app.listen() into mongoose connect. This would make sure you can only run development on your preferred PORT only when it has successfully connected to your Database. e.g From your code
mongoose.connect(uri)
.then(() => {
//listen for PORT request
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
}).catch((error) => {
console.log(error);
});
Try purposely using the wrong Username or Password and see if you get this error:
MongoServerError: bad auth : Authentication failed.
at Connection.onMessage (/Users/user/Documents/..<pathway>../connection.js:207:30)
*
*
*
*
ok: 0,
code: 8000,
codeName: 'AtlasError',
[Symbol(errorLabels)]: Set(1) { 'HandshakeError' } }
If you don't get this error then you have a connection problem. To solve this, I added my current IP ADDRESS and 0.0.0.0/0 (includes your current IP address) at the Network Access page. So you click on MY CURRENT IP ADDRESS and confirm upon setting up the network. Go to NETWORK ACCESS, click on add new IP ADDRESS, input 0.0.0.0/0 and confirm. Then try using the wrong username or password in the URI link given to you to see if it gives the above-expected error, then you can now correct the Username and Password, and npm run dev or npm start (However you configured it in your package.json file).
Code issues
First of I would correct your Model.js file from this:
const Quiz = mongoose.model("Quiz", quizSchema);
module.exports = Quiz;
to this:
module.exports = mongoose.model("Quiz", quizSchema);
I can see why yours can work, but it may be an issue as you want to get the schema upon accessing the whole file.
Secondly, I would correct the code for Posting and you can do that in 2 ways using the asynchronous method. Which depends on the method of assigning the req.body.
Way 1:
app.post("/new/", async (req, res) => {
const { title, description, question } = req.body;
//adds doc to db
try {
const quiz = await Quiz.create({ title, description, question });
res.status(200).json(quiz);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
OR
Way2:
app.post("/new/", async (req, res) => {
const quiz = new Quiz(req.body);
//adds doc to db
try {
const savePost = await quiz.save();
response.status(200).send(savePost);
} catch (error) {
response.status(400).send(error);
}
});
NOTE: You don't necessarily have to create a named database and collection in Mongo Atlas before starting the project. The URI given to you covers that if there are no problems with the connection to the DB or the Code.
based on your code
URI:
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
would create a database called: QuizDatabase and collection called: quizs (MongoDb always creates the plural word from the model given and makes it start with lowercase (i.e from your Model.js, the mongoose.model("Quiz"))).
If no database is named in your URI, then a database called test is automatically created for you as a default database, with the collection name being the mongoose.model("") given.
CONCLUSION
This should solve at least 90% of your issues, any other creation/POST problems is currently beyond my current expertise. Happy Coding 🚀🚀🚀

Use single database connection in entire application?

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);

how to use the connection.db.collection function?

I have implemented the following code from this link:
What is best way to handle global connection of Mongodb in NodeJs
to create a class for the connection of MongoDB. But when I try to call the singleton class in the router, I get the following error:
TypeError: Connection.db.collection is not a function
mongodb.js
const MongoClient = require('mongodb').MongoClient
const url = '...';
class Connection {
static connectToDB() {
if ( this.database ) return Promise.resolve(this.database)
return MongoClient.connect(this.url, {useNewUrlParser: true}, (err, db) => {
if (err) console.log(err);
else {
this.db = db;
console.log('MongoDB connected');
}
})
}
}
Connection.db = null
Connection.url = url
Connection.options = {
bufferMaxEntries: 0,
reconnectTries: 5000,
}
module.exports = Connection;
app.js
const express = require('express');
const app = express();
let bodyParser = require('body-parser')
// mongodb config
const Connection = require('../config/mongodb');
const server = app.listen(3000, () => {
Connection.connectToDB(); // output: MongoDB connected
console.log(`listening to port: ${port} on http://127.0.0.1:3000}/`); // output: listening to port: 3000 on http://127.0.0.1:3000/
});
router.js
const router = require('express').Router();
let Connection = require('../config/mongodb');
router.post('/data', (req, res) => {
Connection.db.collection('tweets').find({}) // output: TypeError: Connection.db.collection is not a function
.then(tweets => console.log(tweets))
.catch(err => console.log(err));
});
Try once to package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.
The question you linked uses promises throughout, whereas you're using the callback version of connect.
return MongoClient.connect(this.url, {useNewUrlParser: true}, (err, db) => ...
You then call this without returning in your server:
Connection.connectToDB();
console.log(`listening to port: ${port} on http://127.0.0.1:3000}/`);
There is therefore no guarantee that your connection will have been made by the time your first api request comes in. In fact, if you did:
Connection.connectToDB();
console.log(`listening to port: ${port} on http://127.0.0.1:3000}/`);
Connection.db.collection('tweets').find({});
It would fail every time as Connection.db will still be null.
In the example you linked, using Promises protect against that. Note in particular the connect method:
static connectToDB() {
if ( this.database ) return Promise.resolve(this.database)
// ** USING THE PROMISE VERSION OF CONNECT **
return MongoClient.connect(this.url, this.options)
.then(db => this.db = db)
}
and your usage code should also use promises:
return Connection.connectToDB()
.then(() => {
// do something here
});

how does createConnection work with nodeJS in mysql?

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.

Resources