MongoServerError: command listDatabases requires authentication - mongodb

please help
I've been on this issue for hours now and I really don't know what else to do (and all the research I did didn't provide any solution unfortunately). So I'm asking if anyone can think of an answer why this is not working:
mongodb.conf to
security:
authorization:
enabled
mongo-express work fine
mongodb.conf to
security:
authorization:
enabled
mongo-express not work...
config.js
'use strict';
var url = require('url');
if (typeof process.env.MONGODB_PORT === 'string') {
var mongoConnection = url.parse(process.env.MONGODB_PORT);
process.env.ME_CONFIG_MONGODB_SERVER = mongoConnection.hostname;
process.env.ME_CONFIG_MONGODB_PORT = mongoConnection.port;
}
module.exports = {
mongodb: {
server: process.env.ME_CONFIG_MONGODB_SERVER || 'localhost',
port: process.env.ME_CONFIG_MONGODB_PORT || 27017,
//autoReconnect: automatically reconnect if connection is lost
autoReconnect: true,
//poolSize: size of connection pool (number of connections to use)
poolSize: 4,
//set admin to true if you want to turn on admin features
//if admin is true, the auth list below will be ignored
//if admin is true, you will need to enter an admin username/password below (if it is needed)
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
{
database: 'admin',
username: 'admin',
password: 'adminpass'
}
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || 'admin',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || 'adminpass',
//whitelist: hide all databases except the ones in this list (empty list for no whitelist)
whitelist: [],
//blacklist: hide databases listed in the blacklist (empty list for no blacklist)
blacklist: []
},
site: {
host: '0.0.0.0',
port: 8081,
cookieSecret: process.env.ME_CONFIG_SITE_COOKIESECRET || 'cookiesecret',
sessionSecret: process.env.ME_CONFIG_SITE_SESSIONSECRET || 'sessionsecret',
cookieKeyName: 'mongo-express',
sslEnabled: process.env.ME_CONFIG_SITE_SSL_ENABLED || false,
sslCert: process.env.ME_CONFIG_SITE_SSL_CRT_PATH || '',
sslKey: process.env.ME_CONFIG_SITE_SSL_KEY_PATH || ''
},
//set useBasicAuth to true if you want to authehticate mongo-express loggins
//if admin is false, the basicAuthInfo list below will be ignored
//this will be true unless ME_CONFIG_BASICAUTH_USERNAME is set and is the empty string
useBasicAuth: process.env.ME_CONFIG_BASICAUTH_USERNAME !== '',
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'admin',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'adminpass'
},
options: {
//documentsPerPage: how many documents you want to see at once in collection view
documentsPerPage: 10,
//editorTheme: Name of the theme you want to use for displaying documents
//See http://codemirror.net/demo/theme.html for all examples
editorTheme: process.env.ME_CONFIG_OPTIONS_EDITORTHEME || 'rubyblue',
//The options below aren't being used yet
//cmdType: the type of command line you want mongo express to run
//values: eval, subprocess
// eval - uses db.eval. commands block, so only use this if you have to
// subprocess - spawns a mongo command line as a subprocess and pipes output to mongo express
cmdType: 'eval',
//subprocessTimeout: number of seconds of non-interaction before a subprocess is shut down
subprocessTimeout: 300,
//readOnly: if readOnly is true, components of writing are not visible.
readOnly: false
},
// Specify the default keyname that should be picked from a document to display in collections list.
// Keynames can be specified for every database and collection.
// If no keyname is specified, it defalts to '_id', which is a mandatory feild.
// For Example :
// defaultKeyNames{
// "world_db":{ //Database Name
// "continent":"cont_name", // collection:feild
// "country":"country_name",
// "city":"name"
// }
// }
defaultKeyNames: {
}
};
please help.... please help

Related

How to connect PostgreSQL Database to Cypress 10+ , no pg_hba.conf entry error

When I try to connect and query on my PostgreSQL database, I keep getting a cypress error: “no pg_hba.conf entry for host “ user “postgres”, database “postgres”, SSL off”. How do I solve the error. Is this an issue with code or with the database?
this is my cypres.config.js file:
const pg = require("pg")
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on("task", {
//create a task - take two parameters - first being a config and second is sql
READFROMDB({ dbConfig, sql }) {
//create a client using the config argument
const client = new pg.Pool(dbConfig)
//return thw result from sql
return client.query(sql)
}
})
},
DB:{
database: "<name>",
user: "<name>",
password: "<pw>",
host: "<hostname>.amazonaws.com", //not localhost
port: 5432,
dialect: "postgres",
dialectOptions: {
ssl: {
require: true, // This will help you. But you will see nwe error
rejectUnauthorized: false // This line will fix new error
}
}
}
}
})
This is my test:
cy.task("READFROMDB",{
//get config from db
dbConfig: Cypress.config('DB'),
//SQL we want to perform
sql: 'select * from user where user=\'Phoebe\''
}).then((result)=>{
console.log(result.rows)
})

Can't connect database with postgraphile

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.

Unhandled promise rejection: Error: URL malformed, cannot be parsed

I am new to aws and mongodb at the same time, so I'm stuck at a very basic point in trying to connect to my mongo databse, hosted on an amazon linux ec2 instance. The reason is, I'm not able to build the path to my database.
Here is what I'm trying to use:
mongoose.connect('mongod://ec2-user#ec2-XX-XX-XXX-XXX-XX.compute-1.amazonaws.com:27017/test' )
And here is the result of my test lambda function:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: URL malformed, cannot be parsed
I'm using mongodb 3.6.5.
Mongoose 5.x supports following syntax for authorization and also make sure you have not used any special character in url like #,-,+,>
mongoose.connect(MONGO_URL, {
auth: {
user: MONGO_DB_USER,
password: MONGO_DB_PASSWORD
}
})
Or if you want to remove deprication warning Avoid “current URL string parser is deprecated"
Add option useNewUrlParser
mongoose.connect(MONGO_URL, {
auth: {
user: MONGO_DB_USER,
password: MONGO_DB_PASSWORD
},
{ useNewUrlParser: true }
})
My issue was a more simple URI issue. Since there was an # character in the mongod address.
I had to use this:
return mongoose.connect(encodeURI(process.env.DB_CONNECT)); //added ');'
If you used the following URI in your environment file for example
MongoDB://<dbuser>:<dbpassword>#ds055915.mlab.com:55915/fullstack-vue-graphql
Make sure your password inMONGOD_URI does not have a special character like #. I had used # as part of my password character and was getting the error. After I removed special characters from my DB Password, all worked as expected.
In my case the below worked fine.
Inside db.js
const mongoose = require('mongoose');
const MONGODB_URI = "mongodb://host-name:27017/db-name?authSource=admin";
const MONGODB_USER = "mongouser";
const MONGODB_PASS = "myasri*$atIP38:nG*#o";
const authData = {
"user": MONGODB_USER,
"pass": MONGODB_PASS,
"useNewUrlParser": true,
"useCreateIndex": true
};
mongoose.connect(
MONGODB_URI,
authData,
(err) => {
if (!err) { console.log('MongoDB connection succeeded.'); }
else { console.log('Error in MongoDB connection : ' + JSON.stringify(err, undefined, 2)); }
}
);
Note:
My Node version is 10.x
MongoDb server version is 3.6.3
mongoose version is ^5.1.2
I just want update the answer from #anthony-winzlet, because I have same error and I has solve with this code.
mongoose.connect(url, {
auth: {
user:'usrkoperasi',
password:'password'
},
useNewUrlParser:true
}, function(err, client) {
if (err) {
console.log(err);
}
console.log('connect!!!');
});
I just add callback and useNewUrlParser:true. I use "mongoose": "^5.2.7",.
Happy coding!
If you deployed your app to Heroku make sure you updated the Config Vars as they are in your .env file. At least, this was my case.
I know this question has accepted answer, but this is what worked for me:
I'm using Mongoose 6.0.5 and Mongodb 5.0.6, with authentication enabled and with special character (%) in the password:
mongoose.connect('mongodb://localhost:27017', {
auth: { username: "myusername", password: "mypassword%" },
dbName: "mydbname",
authSource: "mydbname",
useNewUrlParser: true,
useUnifiedTopology: true,
}, function(err, db) {
if (err) {
console.log('mongoose error', err);
}
});
Many solutions had only user and pass for auth that needed username and password instead. Also it needed dbName to get access to mydb's collections.
I have same problem but problem with password
should'nt special character
password not use like this Admin#%+admin.com wrong
password use like this Admin right
or any password you wanna use

I can not link my mlab database address in meteor up

I am trying to deploy my meteor application to digitalocean. I have set my mlab database address in the mup.js in the environment variables, but when I log into my mlab profile to manage my database. My application does not register the data in the mlab address but in another part that I do not know where. When I set my address in mup.js in the environment variables.
Where is this application inserting data? Because it is not doing it in my mlab address as I defined it before.
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
pem: '~/.ssh/id_carlo_digital'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
},
app: {
// TODO: change app name and path
name: 'perfilesgs',
path: '.',
servers: {
one: {},
},
buildOptions: {
serverOnly: true,
},
env: {
// TODO: Change to your app's url
// If you are using ssl, it needs to start with https://
ROOT_URL: 'http://1.2.3.4',
MONGO_URL: 'mongodb://user:pass#mlab_server:port/perfilesgs',
},
// ssl: { // (optional)
// // Enables let's encrypt (optional)
// autogenerate: {
// email: 'email.address#domain.com',
// // comma separated list of domains
// domains: 'website.com,www.website.com'
// }
// },
docker: {
// change to 'kadirahq/meteord' if your app is using Meteor 1.3 or older
image: 'abernix/meteord:base',
prepareBundle: false
},
// Show progress bar while uploading bundle to server
// You might need to disable it on CI servers
enableUploadProgressBar: true
},
mongo: {
version: '3.4.1',
servers: {
one: {}
}
}
};
According to this you just have to get rid of this part:
mongo: {
version: '3.4.1',
servers: {
one: {}
}
}

how to make mongo-express show all db?

here is my mongo-express config, when i login http://192.168.1.104:8081, it only shows the admin db, i want it to show all db. i had ran this command before
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
}
)
config file:
'use strict';
var url = require('url');
if (typeof process.env.MONGODB_PORT === 'string') {
var mongoConnection = url.parse(process.env.MONGODB_PORT);
process.env.ME_CONFIG_MONGODB_SERVER = mongoConnection.hostname;
process.env.ME_CONFIG_MONGODB_PORT = mongoConnection.port;
}
module.exports = {
mongodb: {
server: process.env.ME_CONFIG_MONGODB_SERVER || 'localhost',
port: process.env.ME_CONFIG_MONGODB_PORT || 27017,
//autoReconnect: automatically reconnect if connection is lost
autoReconnect: true,
//poolSize: size of connection pool (number of connections to use)
poolSize: 4,
//set admin to true if you want to turn on admin features
//if admin is true, the auth list below will be ignored
//if admin is true, you will need to enter an admin username/password below (if it is needed)
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
/*
* Add the the name, the username, and the password of the databases you want to connect to
* Add as many databases as you want!
{
database: 'test',
username: 'user',
password: 'pass'
}
*/
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || '',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || '',
//whitelist: hide all databases except the ones in this list (empty list for no whitelist)
whitelist: [],
//blacklist: hide databases listed in the blacklist (empty list for no blacklist)
blacklist: []
},
site: {
host: '192.168.1.104',
port: 8081,
cookieSecret: process.env.ME_CONFIG_SITE_COOKIESECRET || 'cookiesecret',
sessionSecret: process.env.ME_CONFIG_SITE_SESSIONSECRET || 'sessionsecret',
cookieKeyName: 'mongo-express',
sslEnabled: process.env.ME_CONFIG_SITE_SSL_ENABLED || false,
sslCert: process.env.ME_CONFIG_SITE_SSL_CRT_PATH || '',
sslKey: process.env.ME_CONFIG_SITE_SSL_KEY_PATH || ''
},
//set useBasicAuth to true if you want to authehticate mongo-express loggins
//if admin is false, the basicAuthInfo list below will be ignored
//this will be true unless ME_CONFIG_BASICAUTH_USERNAME is set and is the empty string
useBasicAuth: process.env.ME_CONFIG_BASICAUTH_USERNAME !== '',
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'root',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'password'
},
options: {
//documentsPerPage: how many documents you want to see at once in collection view
documentsPerPage: 10,
//editorTheme: Name of the theme you want to use for displaying documents
//See http://codemirror.net/demo/theme.html for all examples
editorTheme: process.env.ME_CONFIG_OPTIONS_EDITORTHEME || 'rubyblue',
//The options below aren't being used yet
//cmdType: the type of command line you want mongo express to run
//values: eval, subprocess
// eval - uses db.eval. commands block, so only use this if you have to
// subprocess - spawns a mongo command line as a subprocess and pipes output to mongo express
cmdType: 'eval',
//subprocessTimeout: number of seconds of non-interaction before a subprocess is shut down
subprocessTimeout: 300,
//readOnly: if readOnly is true, components of writing are not visible.
readOnly: false
},
// Specify the default keyname that should be picked from a document to display in collections list.
// Keynames can be specified for every database and collection.
// If no keyname is specified, it defalts to '_id', which is a mandatory feild.
// For Example :
// defaultKeyNames{
// "world_db":{ //Database Name
// "continent":"cont_name", // collection:feild
// "country":"country_name",
// "city":"name"
// }
// }
defaultKeyNames: {
}
};
Remarks:
in above config,
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'root',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'password'
},
i changed the username, password to root and password repectively, when i access http://192.168.1.104:8081 , i need to enter root and password in http auth prompt so as i entering the mongo-express web panel.
This is my first answer on StackOverflow, but hopefully it's helpful.
Issue in your case seems to be database authentication defined in config.js.
You need to pass the db credentials through "auth" section and not through "basicAuth".
Also, once you correct the config.js file, start the mongo-express with -a switch, i.e. -> cd YOUR_PATH/node_modules/mongo-express/ && node app.js -a
Corrected section of config.js :
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
/*
* Add the the name, the username, and the password of the databases you want to connect to
* Add as many databases as you want!
{
database: 'test',
username: 'user',
password: 'pass'
}
*/
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || 'root',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || 'password',