Getting error trying to create Postgres DB in Node.js - javascript

Im learning Node and trying create a server using Express and connecting it to a postgres db and keep getting the following when I run node server.js:
events.js:72
throw er; // Unhandled 'error' event
^
error: role "username" does not exist
at Connection.parseE (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:526:11)
at Connection.parseMessage (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:356:17)
at Socket.<anonymous> (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:764:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:426:10)
at emitReadable (_stream_readable.js:422:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
my server.js file looks like this:
// app dependencies
var express = require("express");
var Sequelize = require("sequelize");
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
//middleware
app.use(bodyParser());
app.use(morgan('dev'));
//sequalize initialization
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
var employerRoute = require("./routes/employer")(sequelize);
//sync the model with the database
sequelize.sync().success(function (err) {
app.get("/employer", employerRoute.get);
app.post("/employer", employerRoute.create);
app.listen(5000);
});
I have postgres running. Do I need to create a new db in the command-line then run $psql to create username/password? Shouldn't the db get created automatically?

You can use
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
for connecting to postgresql database, but sequelize does not create nor user nor database for you. You must do it yourself. Use createuser and createdb postgres utilities to create them, or user -c flag of psql command. You also must have privilege to do it, so in the next example commands run using postgres user:
su postgres -c "psql -U postgres -c \"CREATE USER username WITH ENCRYPTED PASSWORD 'password'\""
su postgres -c "psql -U postgres -c \"CREATE DATABASE jobletics WITH OWNER=username ENCODING='UTF8'\""

Although Sequelize does not have a method to create databases, you can use the create query method to execute a custom method.
But the catch is the following,
You need to "connect to a database" to execute any command
Here you can't do that because it's that database creation command that you would want to create in the first place.
There's one simple way to overcome this. Postgress has two inbuilt template DBs that cannot be dropped called template0 and template1 respectively. More on template databases here
So all you have to do is connect to template1 (not template0) in your connection string
const sequelize = new Sequelize('postgres://username:password#localhost:5432/template1')
and execute the sequelize query method with the create query command
const createQuery = "CREATE DATABASE YOUR_DB_NAME WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252' TABLESPACE = pg_default CONNECTION LIMIT = -1;"
sequelize.query(createQuery)
.then(() => console.log("DB created"))
.catch(err => console.log("error creating DB", err))

I have not seen the database getting created automatically. When I use sequelize.js, i normally run it within a vm which has a puppet manifest to assert that the database already exists.
Also, when it comes to connecting to the db, I would normally do it like so as I think it is easier to read:
var Sequelize = require("sequelize");
var sequelize = new Sequelize(
"dbName",
"username",
"password",
{
"dialect": "postgres",
"port": 5423
}
);
Finally, make sure that postgres existing in your package.json, if is doesn't you will have to run the following:
npm install --save pg pg-hstore

Related

MongoServerError: Authentication failed when using mongo and mongo express with docker containers

I am learning docker so I was following one of the video it shown that how to connect your js app with mongoDB when it is running in docker containers . Now little variation I did is that it shown to connect mongo on system port 27017 which is default mongo port but the problem is I don't want to connect to my system installed mongo but to the container mongo , so for that purpose I decided to run mongo container on port 3535. When I did so mongo-express successfully got connected to mongo but when I am trying to connect it with my js app(using mongoose ) it is continuously showing errors with authentication error I have checked password is correct , no brackets issue is their , the command I used to turn up my docker containers are
docker run -d -p 3535:27017 --name mongoDB --network databases -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin mongo
and another one for mongo-express is
docker run -d -p 8081:8081 --name mongoExp --network databases -e ME_CONFIG_BASICAUTH_USERNAME=admin -e ME_CONFIG_BASICAUTH_PASSWORD=admin -e ME_CONFIG_MONGODB_SERVER=mongoDB -e ME_CONFIG_MONGODB_AUTH_USERNAME=admin -e ME_CONFIG_MONGODB_AUTH_PASSWORD=admin mongo-express
My node app code looks like
const mongoose = require('mongoose');
const {Humans}= require("./models/humans.js")
mongoose.connect('mongodb://admin:admin#localhost:3535/user', {useNewUrlParser: true, useUnifiedTopology: true }).then(()=>{
console.log("connected to db");
})
let data={
name:"Vaibhav Jain",
mob:"9801",
skills:"coding"
}
const express = require('express')
const app = express();
app.set('view engine', 'ejs');
app.get("/",async(req,res)=>{
// console.log(Humans);
// await Humans.insertMany( );
// await Humans.insertMany({name:"Mobius" , mob:"5908922",skills:"drawing"});
const result = await Humans.find();
res.send(result);
})
app.get("/home",(req,res)=>{
res.render("home", data);
})
app.listen(3000,()=>{
console.log("listening port");
})
Also one thing i would like to mention I have created a user database which have a collection human , this all I created from UI but I wanted to connect it to my app using mongoose , so for that Human which is shown to be imported is actually empty schema (read that from somewhere that you can use existing collections in such a way please correct me on this part also if I am wrong )
Just for refrence current my docker is in this state
You may not have created user for the database user after created it using UI. In your case, you can run this query to create a normal user.
> use user
> db.createUser({user: "user", pwd: "user", roles:["dbOwner"]})
After that, you can connect to user database using this string mongodb://user:user#localhost:3535/user
Check out document db.CreateUser.

Error: read ECONNRESET when connected to a mysql server with Node.js

I'm trying to establish a simple connection to my database with the mysql npm package. At first glance, everything works fine and I can get the information I need, however, if I leave the server running for some time I get the following error:
Error: read ECONNRESET
at TCP.onStreamRead
const express = require('express');
const app = express();`
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'XXXX.mysql.database.azure.com',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX'
})
db.connect((err)=>{
if(err){
console.log(err.message);
} else {
console.log('Connected to the database');
}
})
As far as I understand the problem stems from the database connection being in idle mode. Do I need to configure the Azure server or is there something else I need to do?
Couple of things to try:
You can try creating connection pool instead of **createConnection**
mysql.createPool({});
Modify your package.json like below:
"dependencies": {
"mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
},
It is described in detail here:
Bad handshake or ECONNRESET Azure Mysql Nodejs
https://social.msdn.microsoft.com/Forums/en-US/c8fedbcc-909d-41ce-8c72-0374f76fdf82/cannot-connect-from-nodejs?forum=AzureDatabaseforMySQL
Hope it helps.

MongoDB/Mongoose Connection Error when Dbname is used in the connection string

A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.
The connection can be established when we use
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri)
Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)
and also tried
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.
Why is it unable to make the connection and how can we solve this problem?
Update
Found the solution to be
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })
Why must the dbname be passed as an option instead of including it in the connection string?
This has worked for me, thanks.
var result = await mongoose.connect('mongodb://root:example#localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})
Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)
Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.

Node.JS Web Application Create MongooseDB Connection

I'm trying to create a connection to MongoDB from a Node.JS application but I can't get the connection working. I just get errors saying:
TypeError: mongoose.createConnection is not a function
Same for just mongoose.connection also..
I just have a serivce class and I'm trying to create a connecting inside of it:
const mongoose = require('mongoose');
export class MongoDbService{
constructor(){
db = mongoose.createConnection(url)
.on('error', console.error.bind(console, 'connection error:'))
.once('open', function callback() {
console.log('db connection open');
});
console.log(db);
}
Surely this is possible ???
I'm trying to build a web application that talks to mongodb, nothing fancy at all.. Mongoose v5.1.6 is install also.

Can't start MongoDB on localhost for node.js

I am a beginner to node.js and MongoDB. I am trying to setup a basic project like so.
In my project dir I run node init, accept the default values and then run npm install --save mongodb. In my index.js I have the following code:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Now when I run node index.js I get the following error:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
I have tried changing the port number but still get the same error. What am I doing wrong here?
By default the MongoDB server is running on port 27017. You need to change the connection string to mongodb://localhost:27017/mydb.
First you need to install MongoDB if you don't already have it installed. Visit MongoDB site to download.
Follow the instructions there on how to start it up and running, after that try running your app again.
Also by default MongoDB runs on port 27017 so your url should point to localhost:27017.
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Categories