I am running the following command from my command line
npm models/database.js
I am getting the error:
password authentication failed for user "marco"
this is my connection code and its stored in my Database.js file within my models folder at the root level of my project.
var pg = require('pg');
// var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/NodeTestProject';
var connectionString = "postgres://marco:Easye123#localhost:5432/NodeTestProject";
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('CREATE TABLE users(id SERIAL PRIMARY KEY, FirstName VARCHAR(40) not null, LastName VARCHAR(40) not null, MiddleName VARCHAR(40) not null, Email VARCHAR(40) not null, UserName VARCHAR(40) not null, Password VARCHAR(40) not null');
query.on('end', function() { client.end(); });
I am 100% sure that when I set up Postgresql I set the password to "Easye123" I can log in to Postgresql no issues and I have created a database called NodeTestProject. Do i have to create a user for the NodeTestProject database? Am I missing a step? Any feedback would be appreciated.
To whoever is new to Postgresql
The credentials you put on your connection file are not the same as the SuperUser you set up while installing Postgresql. Within your pgAdminIII you must create a Group Role and allow that Group Role to "Can Login" once that is set up declare the owner of the Database as that Group Role User. Finally declare that GroupRole user as the username and the password you used for it as the password in your connection string.
var pg = require('pg');
var conString = "postgres://Marco:12345#localhost:5432/NodeTestProject";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
I can now successfully log into this local database and interact with it.
Related
I'm trying to connect to my PostgreSQL database hosted on Heroku through Auth0's Database Connections.
I am getting an error when I try to invoke the Get User script within Auth0's database actions:
no pg_hba.conf entry for host "xx.xxx.xx.x", user "xxx", database "xxx", no encryption
The script looks like this:
function loginByEmail(email, callback) {
const postgres = require('pg');
const conString = configuration.DATABASE_URL;
postgres.connect(conString, function (err, client, done) {
if (err) return callback(err);
const query = 'SELECT id, nickname, email FROM organizations WHERE email = $1';
client.query(query, [email], function (err, result) {
done(); // Close the connection to the database
if (err || result.rows.length === 0) return callback(err);
const user = result.rows[0];
return callback(null, {
user_id: user.id,
nickname: user.nickname,
email: user.email
});
});
});
}
Connection String:
configuration.DATABASE_URL: 'postgres://xxx:xxx#xxx?sslmode=require'
I appended sslmode=require to the end of my connection string to ensure I have a SSL connection to my database.
I have also tried changing sslmode=require to ssl=true, which results in a different error:
self signed certificate
I am unsure where to go from here, so any help would be appreciated.
You should first establish the client and specify the rejectUnauthorized flag, like so:
const client = new postgres.Client({
connectionString: conString,
ssl: { sslmode: 'require', rejectUnauthorized: false }
});
Then, instead of using your postgres to connect, use the client:
client.connect();
client.query(...);
This should solve your problem, and the connection will be encrypted. You won't, however, be protected against Man-In-The-Middle (MITM) attacks, as specified in documentation.
#Pexers solution worked for me, however, somehow it shows TypeScript error. The way I did it is just ssl: true:
const client = new postgres.Client({
connectionString: conString,
ssl: true
});
As per the stackoverflow question HERE postgres column does not store dashes for the UUID data type
Yet when I load the value of any UUID column using pg-promise it always shows dashes
How do I retrieve these UUIDs without dashes using pg-promise
Code sample illustrating the problem
var pgPromise = require("pg-promise"),
pgp = pgPromise({}),
db = pgp({
database: "mydatabase",
host: "localhost",
password: "somepass",
port: 5432,
ssl: false,
user: "myuser"
});
pgp.pg.types.setTypeParser(20, parseInt);
db.query("CREATE TABLE test(myid uuid not null primary key)")
.then((e => {
var r = require("crypto").createHash("md5").update("test data").digest("hex");
return db.query("INSERT INTO test(myid) VALUES($1) ON CONFLICT DO NOTHING", [r])
}))
.then((e => db.query("SELECT * FROM test")))
.then((e => (console.log(e), db.query("DROP TABLE test"))))
.then((() => console.log("test success!")))
.catch((e => console.error(e)));
This line did the trick
pgp.pg.types.setTypeParser(pgp.pg.types.builtins.UUID, (val) => {
val === null ? null : val.replace(/-/g, '')
});
Thank you for your suggestions #vitaly-t and #Bergi
I have an instant of mongodb in the server , ana i connect my meteor app to this DB using that code : lib/connection.js
MONGO_URL = 'mongodb://xxxxxxxx';
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect(MONGO_URL, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to cc', MONGO_URL);
var collection = db.collection('test');
var test1= {'hello':'test1'};
collection.insert(test1);
db.close();
}
});
the connextion to the the external mongo is established and the collection test is created in the server but my app still connected to the the local mongo when i insert my collection: books:
thee code : collections/Books.js
Books= new Mongo.Collection('books');
BooksSchema= new SimpleSchema({
name: {
type: String,
label: "Name"
autoform:{
label: false,
placeholder: "schemaLabel"
}
},
categorie:{
type: String,
label: "Categorie"
autoform:{
label: false,
placeholder: "schemaLabel"
}
},
});
Meteor.methods({
deleteBook: function(id) {
Cultures.remove(id);
}
});
Books.attachSchema(BooksSchema);
code client/books.html
<template name="books">
<p>add new books </p>
{{> quickForm collection="Books" id="newBook" type="insert" class="nform" buttonContent='ajouter' buttonClasses='btn bg-orange'}}
</template>
help bleaaaaaz
You should specify the database that is supposed to be used in MONGO_URL environment variable, not in your code. If you work locally start your application like this:
MONGO_URL="mongodb://xxxxxxxx" meteor
UPD
Don't know about Windows. See this SO question.
Looks like you should set env vars in windows like this:
set MONGO_URL=mongodb://localhost:27017/mydbname
ok thnk you Ramil , i create a new system environment variable on windows , MOGO_URL with value equal : mongodb://xxxxxxxx, and it works; the application is connected to the database in the server , and the data is inserted into it .
now my problem is how to get the data from that DB , I user Microsoft azure to stock the db with API DocumentDB
I'm trying to store users on my own mongo database not the default (auth0 server).
Below is the script:
function create (user, callback) {
mongo('mongodb://admin:pass#localhost:27017/mydb', function (db) {
var users = db.collection('subscribers');
users.findOne({ email: user.email },
function (err, withSameMail) {
if (err) return callback(err);
if (withSameMail) return callback(new Error('the user already exists'));
user.password = bcrypt.hashSync(user.password, 10);
users.insert(user, function (err, inserted) {
if (err) return callback(err);
callback(null);
});
});
});
}
This is the error I'm getting when I try to create a user:
[Error] Error: socket hang up
at createHangUpError (_http_client.js:200:15)
at Socket.socketOnEnd (_http_client.js:285:23)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)
Your mongodb is in localhost (see your connection string). The create script runs in Auth0 servers, so localhost (your machine) is not reachable.
Normally your instance would run on a server that is reachable from Auth0 (e.g. mongolabs, a server in AWS, etc). If you are testing, then you might want to check out ngrok
Blakes suggestion of caching the connection is a good one, but it is an optimization, not the reason it is not working.
This is a very weird problem with "connect-mongo"
In my server, I have two scripts.
1) create the express server with session with Mongo DataStore: It has no problem for connection or creating the session.
MongoStore = require('connect-mongo'),
app = require('express').createServer(
express.session({ secret: cfg.wiki_session_secret,
store:new MongoStore({
db: 'mydatabase',
host: '10.10.10.10',
port: 27017
})
})
);
2) just create the store without express:
var MongoStore = require('connect-mongo');
var options = {db: 'mydatabase'};
var store = new MongoStore(options, function() {
var db = new mongo.Db(options.db, new mongo.Server('10.10.10.10', 27017, {}));
db.open(function(err) {
db.collection('sessions', function(err, collection) {
callback(store, db, collection);
});
});
});
That will throw the connection problem:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Error connecting to database
at /home/eauser/node_modules/connect-mongo/lib/connect-mongo.js:106:13
at /home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:79:30
at [object Object].<anonymous> (/home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connections/server.js:113:12)
at [object Object].emit (events.js:64:17)
at Array.<anonymous> (/home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection.js:166:14)
at EventEmitter._tickCallback (node.js:126:26)
I just don't know why..
connect-mongo is a middleware for the connect framework, which express is based on.
So, you must use the middleware with the express framework or the connect framework, otherwise it won't work. It's not written to be a standalone session library.
You can go for mongoose to connect. Install using npm command
npm install mongoose
Install mongoose globally
npm install -g mongoose
app.js
var mongoose = require("mongoose");
This module has callback in the constructor which is called when the database is connected, and the collection is initialized so it won't work as you expect.
I've the same problem than you and I wanted the same interface that you aim here. So I wrote another module called YAMS - Yet Another Mongo Store. This is an example with YAMS:
var MongoClient = require("mongodb").MongoClient;
var Yams = require('yams');
var store = new Yams(function (done) {
//this will be called once, you must return the collection sessions.
MongoClient.connect('mongo://localhost/myapp', function (err, db) {
if (err) return done(err);
var sessionsCollection = db.collection('sessions')
//use TTL in mongodb, the document will be automatically expired when the session ends.
sessionsCollection.ensureIndex({expires:1}, {expireAfterSeconds: 0}, function(){});
done(null, sessionsCollection);
});
});
app.usage(express.session({
secret: 'black whisky boycott tango 2013',
store: store
}));
This is in my opinion more flexible than the connect-mongo middleware.