Authentication failing connecting node.js with PostgreSQL - node.js

I have some of a database set up with PostgreSQL, and I am able to do everything I need from the psql REPL sort of thing, but when I try to access this though node.js on the same machine I get an password authentication filed for user"[my user name]" error.
As per an online tutorial, my database acces code is something like this:
var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
query.on('end', function() { client.end(); });
But as I already have the tables set up with some of my own functions, I'm simply trying to access those functions on POSTs, with:
var express = require('express');
var router = express.Router();
var pg = require('pg');
var path = require('path');
var connectionString = 'postgres://localhost:5432/[My User Name]?ssl=true;
router.post('/locations', function(req,res) {
var client = new pg.Client(connectionString);
client.connect();
var query = client.query([Call to my function, works in REPL, something like "SELECT * FROM create_location([Data from req])"]);
});
I have my pg_.conf set up as:
local all postgres peer
local all all trust
local all all 127.0.0.1/32 trust
host all all ::1/128 md5

your connectionstring seems to be wrong. a connection string has to be like:
postgres://[username]:[password]#[host]:[port]/[databasename]
and in your case:
postgres://[username]#localhost:5432/[databasename]?ssl=true

Related

Not Able to Connect to Password-protected MongoDB Server/DB

After successfully testing my Node app against a local mongoDB db, I am now trying to connect to our server db - which, unlike my local mongoDB, is user and password protected.
I am running into issues while trying the connection to the server. Specifically, I am getting this error:
MongoError: MongoClient must be connected before calling
MongoClient.prototype.db
The creds I'm trying look something like this:
{
"MONGO_URL": "mongodb://myuser:mypassword#someurl.com:27017?authSource=admin",
"MONGO_DATABASE": "bta",
"MONGO_COLLECTION": "jobs"
}
And here is my connection code:
const config = require('./configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
async function getJobDetails() {
client.connect(async function () {
try {
const db = await client.db(dbName);
// do stuff
});
} catch (error) {
console.log(error);
}
});
}
What am I missing here?
I figured out what the issue was and was able to get it to connect. The issue was that the site is secure, so I had to add ssl=true to the url connection string:
const url = 'mongodb://user:password#someurl.com:27017/bta?ssl=true&authSource=admin';
try:
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(url, { useNewUrlParser: true }, function(client_err, client) {
if (client != null) {
var client_db = client.db(dbName);
}
client.close();
});
As MongoDB.
https://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
And please Try double checking DB on the server if it has the right config.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL with password example
const url = 'mongodb://user:password#address:27017?readPreference=primary&authSource=admin';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
This works for both valid localhost/server url

Unable to query MongoDB using a localhost URL and MongoJS

This is the tasks.js code I'm trying to run:
/*jslint node:true*/
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://localhost:27017/tasks', ['tasks']);
router.get('/tasks', function (req, res, next) {
'use strict';
db.tasks.find(function(err, tasks) {
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
The code is meant to query and display all the contents of the json file.
When I replace the db localhost URL with this mLab URL:
var db = mongojs('mongodb://username:password#ds161008.mlab.com:61008/mytasklist_muhab', ['tasks']);
It works perfectly.
I assume there is a problem with the string. I looked up the connectionString standards in MongoDB docs and I couldn't locate the problem.
I haven't assigned any username or password to the local database.
Mongod is running fine and I am able to run commands on the same database using the Mongo shell without any problem.
According to mongojs documentation you may no need to use mongodb://localhost:27017 as part of your connectionString for local db can try by only dbName
like:
var db = mongojs('tasks', ['tasks'])
or
var db = mongojs('tasks')
var mycollection = db.collection('tasks')
and checked your connection established or not by using error or connect event
var db = mongojs('tasks', ['tasks'])
db.on('error', function (err) {
console.log('database error', err)
})
db.on('connect', function () {
console.log('database connected')
})

node.js / mongodb file structure

I'm trying to set up this simnple NodeJS/mongodb app and I have my files structured like this:
server.js
|
+-routes/menu.js
+-routes/cases.js
In my server.js I declare my mongodb vars like this:
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
MongoClient = mongo.MongoClient,
Db = mongo.Db,
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser'),
server = new Server('host.mongohq.com', 10066, {auto_reconnect : true}),
db = new Db('myDb', server);
db.open(function(err, client) {
client.authenticate('myUser', 'myPassword', function(err, success) {
console.log('Authenticated');
});
});
var cases = require('./routes/cases'),
menu = require('./routes/menu');
But then when I try to reference my db var in eg menu.js like this:
db.collection(myCollection, function(err, collection) {});
I get an error that db is not defined.
Obviously I can move all the mongodb declarations down to both my menu.js and cases.js file but that's just very elegant. So how do I create one mongodb instance var and refer to it from my included files?
Thanks in advance...
You need to require server.js in your menu.js file.
Your db object isn't global. If you want it to be, declare it without var.

node.js mongo db write concern

I am running node.js 10.22, windows 8 and mongodb not sure what version, but I just downloaded it today, when I run my code I am getting a message, please ensure you set the default write concern, I am trying to follow a YouTube video, and there is mention of this, and I am finding little about it on the internet, from what i found, when I set the db i should set j:true, or safe : true/false, but neither not working for me. I do get the console log that I'm connected and the host and port, but then I get the write concern message and can't type or do anything.
var mongo = require('mongodb');
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodeintro", new mongo.Server(host,port,{Fsync: true}));
db.open(function(error){
console.log("we are connected"+host + port);
})
Tried this all type of ways as well, still no luck, best i did was get back to the db write concern message, but was not able to even connect this time. What I'm really looking for is to be able to insert anything in mongo db, and i can figure out the rest.
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var host = "127.0.0.1";
var port = mongo.DEFAULT_PORT;
ArticleProvider = function(host, port) {
this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(error){
if(error){
console.log(error)
}
else{
console.log(port,host)
}
});
};
ArticleProvider(host,port)
When using mongodb-native directly, you should now use MongoClient.connect to open a database connection pool. It will set a default write concern for you.
var mongodb = require('mongodb');
mongodb.MongoClient.connect('mongodb://localhost/nodeintro', function(err, db) {
// db is your open nodeintro database connection pool here
});
MongoClient was a somewhat recent addition so the tutorial you're working from likely pre-dates it.
If you use {w:1} parameter in your insert or update operation, you might give this error. To overcome you can use {journal:true} parameter in your db settings.
For instance;
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON;
var db = new Db('Your DB Name', new Server('192.168.170.128', 27017), { journal : true });
db.open(function(err, db) {
var collection = db.collection('user');
collection.findOne({'_id':req.session.User._id}, function(err, user){
// some codes what do you want
collection.save( user, {w: 1}, function(err, user_id) {
// just close the db connection
db.close();
});
});
});

can't connect to mongolab with node.js on heroku

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;

Resources