Can't connect database with postgraphile - postgresql

I have a database in pgadmin name "mydatabase" and the tablename is "mytable". It runs in http://127.0.0.1:33859/browser/. I was trying to use postgraphile to connect with it. Here is the code
const express = require("express");
const { postgraphile } = require("postgraphile");
const app = express();
app.use(postgraphile("postgres://postgres:postgres#localhost:33859/mydatabase -s public"));
app.listen(3000);
My superuser username is "postgres" and password is "postgres". The database is owned by a user named "test" with password "1234". After running the script with node, there is no error at the terminal. When I hit the port 3000, it shows Cannot GET /. Any help on this?

Because the PostGraphile middleware is expected to be mounted along with the rest of your Node.js app, it doesn't take over the root URL and instead makes the GraphQL endpoint available at /graphql by default. To change this there are the graphqlRoute and graphiqlRoute options documented in the Library Usage page.
Here's some good options to get you started:
const isDev = process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "staging";
const DB = "postgres://postgres:postgres#localhost:33859/mydatabase -s public";
const SCHEMA = "public";
app.use(postgraphile(DB, SCHEMA, {
// Enable the GraphiQL IDE in development
graphiql: isDev,
// Add some enhancements (headers, formatting, etc)
enhanceGraphiql: isDev,
// Makes GraphiQL available at http://localhost:3000/ rather than /graphiql
graphiqlRoute: '/',
// Watch DB for changes
watchPg: isDev,
// Use JSON objects rather than strings
dynamicJson: true,
// Debugging
showErrorStack: isDev,
extendedErrors:
isDev
? [
"errcode",
"severity",
"detail",
"hint",
"positon",
"internalPosition",
"internalQuery",
"where",
"schema",
"table",
"column",
"dataType",
"constraint",
"file",
"line",
"routine",
]
: ["errcode"],
// For use with e.g. apollo-link-batch-http
enableQueryBatching: true,
}));
You might find the bootstrap-react-apollo installPostGraphile.js file a good place to get started.

Related

How can I set TLS for Mongoose connection

I'm trying to migrate my mongo database from Compose to IBM Cloud Databases for Mongo and in their documnetations (https://www.compose.com/articles/exporting-databases-from-compose-for-mongodb-to-ibm-cloud/): "With a new Databases for MongoDB deployment, you'll be provided with a replica set of two endpoints to connect to your database. Databases for MongoDB also uses a TLS certificate, so you'll need to configure your MongoDB application driver to accept two hosts and a TLS certificate"
How can I set the TLS certificate provided by IBM Cloud in Mongoose connection ?
Nothing I've tried worked :(
I can see my database if I'm using the IBM cli but from my node.js application I cannot connect to it
var mongoose = require('mongoose');
mongoose.Promise = Promise;
var uri="mongodb://admin:passSftgdsdfvrrdfs#host1-1231243242.databases.appdomain.cloud:32605,host2-1231243242,host1-1231243242/testDatabaseName?authSource=admin&replicaSet=replset"
myDb.db = mongoose.createConnection(uri, {
tls: true,
tlsCAFile:`076baeec-1337-11e9-8c9b-ae5t6r3d1b17` (this is the name of the certificate and is placed in the root)
// tlsCAFile: require('fs').readFileSync('041baeec-1272-11e9-8c9b-ae2e3a9c1b17') // I have also tried something like this
absolute nothing is working even the database is there
Please help me
I'm also facing same problem
this works for me
mongoose.connect(‘mongodb+srv://username:password#host/db_name?authSource=admin&replicaSet=repliasetname&tls=true&tlsCAFile=/root/ca-certificate.crt’,{some config})
Try the following:
var key = fs.readFileSync('/home/node/mongodb/mongodb.pem');
var ca = [fs.readFileSync('/home/node/mongodb/ca.pem')];
var o = {
server: {
ssl: true,
sslValidate:true,
sslCA: ca,
sslKey: key,
sslCert:key
},
user: '****',
pass: '****'
};
m.connect('mongodb://dbAddr/dbName', o)```
I did it locally, you need to install the tunnel first
$ ssh -i "IF YOU HAVE PEM.pem" -L <27017:YOUR_AMAZON_HOST:27017> <server_user_name#server_ip_OR_server_url> -N
I managed to implement it as follows
const CERTIFICATE_PATH = 'rds-combined-ca-bundle.pem'
const certificateCA = CERTIFICATE_PATH && [fs.readFileSync(CERTIFICATE_PATH)];
const sslOptions = certificateCA
? ({
ssl: true,
tlsAllowInvalidHostnames: true,
sslCA: certificateCA,
user: MONGODB_USER,
pass: MONGODB_PASSWORD,
} as ConnectionOptions)
: {};
const options: ConnectionOptions = {
...sslOptions,
};
export const connectMongoDb = async (): Promise<void> => {
await mongoose.connect('mongodb://localhost:27017/test', options);
console.log('📊 Successfully connected to the database');
};
You need to set
MONGODB_USER
MONGODB_PASSWORD

I can not connect to monogdb with mongoose when authorization enabled

I am trying to connect with MongoDB by mongoose. Everything was ok, when I was connecting with my local db where there is no authentication.
When I've tried to connect to other DB with set admin user and credentials, I've got error and I've tried various different options but without any positive result.
I use these versions:
"mongodb": "^3.3.2",
"mongoose": "^5.7.1"
And my server side technology is node.js
I've tried these options:
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}?authSource=admin`,
{ useNewUrlParser: true, useUnifiedTopology: true });
then I've tried this:
let options = {
"auth": { "authSource":"admin"},
"user": "SVSAdmin",
"pass":"8&PG2DCUuDPvy$hx",
"useUnifiedTopology": true,
"useNewUrlParser": true
};
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}, options);
and this:
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=SCRAM-SHA-1')
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=MONGODB-CR')
and also this:
mongoose.connect('mongodb://user:password#host/yourDB?authSource=admin&w=1')
but it does not work. My credentials are ok.
The error message is:
{
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
}
Maybe important thing is that I'm connecting with db by ssh
I would be grateful for any help.
If u are using ur database remotly then u can use it via IP.
db = mongodb://52.221.52.32/DataBaseName

Connected to MLab, but won't connect to localhost

I had this working fine on both localhost and MLab, but then had to switch databases. After much trying I got the database up on MLab, but now it's not connecting to my localhost. Here is my server.js file:
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const mongoose = require("mongoose");
const routes = require("./routes");
// Connect to the Mongo DB
mongoose.connect(process.env.MONGODB_URI || 'mongodb://XXUSERXX:XXPASSWORDXX#ds217388-a0.mlab.com:17388,ds217388-a1.mlab.com:17388/<dbname>?replicaSet=rs-ds217388', { useNewUrlParser: true });
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Add routes, both API and view
app.use(routes);
// Define API routes here
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});
The only line of code I changed was this one below, this is what it was previously:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/wineDB', { useNewUrlParser: true });
I have this app connected in Heroku and had MONGODB_URI defined in the Config Vars, but it wasn't working with the second database until I manually put the connection string in my server.js file. It worked fine with the first one, I don't understand why!
How do I get it to connect to find localhost when it's not running off of MLAB so I can test? Thanks for the help.
It looks like the confusion is from a few different combinations of whether the environment variable being defined or not, as well as whether or not your app is using the variable, instead of falling back to what is defined.
The MONGODB_URI environment variable should contain the connection string for your mLab database and be defined in your Heroku environment both locally and when deployed. I'm assuming that the variable process.env.LOCAL will only be present on your local environment, in situations where your app should be connecting to the local database.
In these cases, something like the following should work:
if(process.env.LOCAL || process.env.MONGODB_URI) {
mongoose.connect(process.env.LOCAL || process.env.MONGODB_URI, { useNewUrlParser: true });
...
} else {
console.log("MongoDB connection string not defined!");
}
We place process.env.LOCAL first, followed the by ||, to say that it gets preference when connecting. Mongoose should then connect to whatever is defined in process.env.LOCAL if present (i.e. your local MongoDB database), falling back to process.env.MONGODB_URI (i.e. mLab) otherwise.
Lastly, it's wrapped in a simple if-else to print out an error message if both values are not defined.

How do I connect to a MongoDB Database using SSL with Loopback

I am trying to connect to a MongoDB Database in Rackspace w/ SSL using loopback, but it's not working. It seems to connect fine; if I enter wrong credentials (on purpose) I get an error message saying "Can't connect", but when I use the correct credentials no error shows so I THINK I'm connecting fine. But when I try to query the database it always timesout, any idea whats happening?
My datasources.json looks something like:
"db": {
"name": "mongodb",
"url": "mongodb://username:password#iad-mongos2.objectrocket.com:port/dbName?ssl=true",
"debug": true,
"connector": "mongodb"
}
I keep reading things about needing a certificate file, but not sure if that applies in this case.
Any help would be greatly appreciated!
use datasources.env.js as below
var cfenv = require('cfenv');
var appenv = cfenv.getAppEnv();
// Within the application environment (appenv) there's a services object
var services = appenv.services;
// The services object is a map named by service so we extract the one for MongoDB
var mongodb_services = services["compose-for-mongodb"];
var credentials = mongodb_services[0].credentials;
// Within the credentials, an entry ca_certificate_base64 contains the SSL pinning key
// We convert that from a string into a Buffer entry in an array which we use when
// connecting.
var ca = [new Buffer(credentials.ca_certificate_base64, 'base64')];
var datasource = {
name: "db",
connector: "mongodb",
url:credentials.uri,
ssl: true,
sslValidate: false,
sslCA: ca
};
module.exports = {
'db': datasource
};
http://madkoding.gitlab.io/2016/08/26/loopback-mongo-ssl/
https://loopback.io/doc/en/lb3/Environment-specific-configuration.html#data-source-configuration
Create a Datasource using lb4 datasource command, edit the datasource generated by adding the SSL details to the config object: 'ssl', 'sslvalidated', 'checkserverIdentity, sslCA, sslKey etc.
import fs from 'fs';
import path from 'path';
const ca = fs.readFileSync(
path.join(__dirname, '../../utils/certs/mongodbca.cert'),
'utf8',
);
const config = {
name: 'test_db',
debug: true,
connector: 'mongodb',
url: false,
host:'hostname',
port: port,
user: 'user',
password: 'password',
database: 'databasename',
authSource: 'admin',
useNewUrlParser: true,
ssl: true,
sslValidate: true,
checkServerIdentity: false,
sslCA: [ca],
};
This worked for me, You can monkey patch the Mongo.connect() function by which you can add the option parameter.
Make a boot script file which can use the MongoDB option parameters of SSL certificate to make a secured connection to MongoDB, below code snippet, is written in a boot script js.
//Below code is written in a boot script
var monog_cert_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/mongodb.pem'));
var monog_ca_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/rootCA.pem'));
var monog_key_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/mongodb.pem'));
const mongoOptions = {
ssl: true,
sslValidate: false,
sslCA:monog_ca_file,
sslKey:monog_key_file,
sslCert:monog_cert_file,
authSource:"auth_db_name"
};
//Patching Mongo connect For option variable
const mongodb = require('mongodb').MongoClient;
const ogConnect = mongodb.connect;
const connectWrapper = function(url,cb) {
return ogConnect(url, mongoOptions, cb);
}
mongodb.connect = connectWrapper;
//Patching Mongo connect For option variable
use datasources.json as below
app_db: {
"host": "127.0.0.1",
"port": 27017,
"database": "test",
"name": "app_db",
"username": "youruser",
"password": "yourpassword",
"connector": "mongodb",
"ssl":true,
"server": {
"auto_reconnect": true,
"reconnectTries": 100,
"reconnectInterval": 1000,
"sslValidate":false,
"checkServerIdentity":false,
"sslKey":fs.readFileSync('path to key'),
"sslCert":fs.readFileSync('path to certificate'),
"sslCA":fs.readFileSync('path to CA'),
"sslPass":"yourpassphrase if any"
}
username,
password,
auto_reconnect,
tries and interval all are optional.
use below link to get the certificates using OpenSSL
https://docs.mongodb.com/manual/tutorial/configure-ssl/

MongoError: auth failed mongoose connection string

I can connect to the DB through terminal, but getting this error using mongoose and gulp.
mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
MongoError: auth failed
My connection string is:
mongodb://usr:psw#localhost:27017/dbname
Any idea what it can be?
I installed MEAN from MEAN packaged by Bitnami for windows 7 using the following password: 123456
Syntax for connection string to connect to mongodb with mongoose module
mongoose.connect("mongodb://[usr]:[pwd]#localhost:[port]/[db]",{auth:{authdb:"admin"}});
If you don't have {auth:{authdb:"admin"}} in the connection string, you will get the following error: MongoError: Authentication failed.
JS Example: mongo-test/app.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://root:123456#localhost/test',{auth:{authdb:"admin"}});
mongoose.set('debug', true); // turn on debug
just add ?authSource=yourDB&w=1 to end of db url
mongoose.connect('mongodb://user:password#host/yourDB?authSource=yourDB&w=1')
this work for me . &w=1 is important
There is many ways to make it work. This is what worked for me [mongoose v5.9.15] :
mongoose.connect('mongodb://localhost:27017/', {
auth: {
user:'root',
password:'example'
},
authSource:"admin",
useUnifiedTopology: true,
useNewUrlParser: true
})
You might want to do something like this...
var opt = {
user: config.username,
pass: config.password,
auth: {
authdb: 'admin'
}
};
var connection = mongoose.createConnection(config.database.host, 'mydatabase', config.database.port, opt);
'authdb' option is the database you created the user under.
mongoose.connect("mongodb://[host]/[db]", { auth:{
authdb: "admin",
user: [username],
password: [pw]
}}).then(function(db){
// do whatever you want
mongoose.connection.close() // close db
})
Do you have a user set up for dbname? By default, no user is required to connect to the database unless you explicitly set one. If you haven't, you should just try to connect to mongodb://localhost:27017/dbname and see if you still get an error.
I have found the solution hier, looks like when you create an user from the mongo shell, it makes SCRAM-SHA-1 instead of MongoDB-CR. So the solution to create a new user with MongoDB-CR authentication.
MongoDB-CR Authentication failed
just make sure that your database is created.
and also if your user is not added in the admin database, then make sure to add it by putting
db.createUser(
... {user:'admin',pwd:'admin',roles:['root']}
... )
This worked for me for mongod --version = db version v3.6.13
mongoose.connect('mongodb://localhost/expressapi', {
auth: {
authdb: "admin",
user: "root",
password: "root",
}
});
mongo mongodb://usr:psw#localhost:27017/dbname
Password should be alphanumeric only
User should be also available in db 'dbname' (Note : Even if user is super admin)
With above changes it connected successfully.
mongoose.connect("mongodb://[usr]:[pwd]#localhost:[port]/[db]",{ authSource: 'admin', useNewUrlParser: true, useUnifiedTopology: true });
I was getting same error. Resolved by adding authSource option to connect function solved the issue. see above code.
The connection string will be like
mongodb://username:password#localhost:27017/yourdbname?authSource=admin