https://www.pipedream.com has an UI-assisted integration with MongoDB. It requires 4 values to connect to the API:
$username
$password
$database
$hostname
my default connect to app connection string is: mongodb+srv://<username>:<password>#cluster0.45xcf.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
(yes, I'm using the default cluster0 and myFirstDatabase values here)
I get back this error response:
MongoAPIError
URI must include hostname, domain name, and tld
DETAILS
at null.resolveSRVRecord (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/connection_string.js:51:25)
at null.connect (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/operations/connect.js:32:57)
at null.null (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/mongo_client.js:127:35)
at null.maybePromise (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/utils.js:409:5)
at MongoClient.connect (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/mongo_client.js:126:41)
at Function.connect (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/mongo_client.js:190:36)
at Object.run (/steps/mongodb.js:19:38)
at global.executeComponent (/var/task/launch_worker.js:171:53)
at MessagePort.messageHandler (/var/task/launch_worker.js:653:28)
I'm trying to connect to the API with:
$username = {REDACTED}
$password = {REDACTED}
$database = myFirstDatabase
$hostname = cluster0
and it's not able to connect, but it does work connecting via mongosh, Compass, etc
here's the full Node.js code Pipedream uses to connect to MongoDB's API:
module.exports = defineComponent({
props: {
mongodb: {
type: "app",
app: "mongodb",
}
},
async run({steps, $}) {
const MongoClient = require('mongodb').MongoClient
const {
database,
hostname,
username,
password,
} = this.mongodb.$auth
const url = `mongodb+srv://${username}:${password}#${hostname}/test?retryWrites=true&w=majority`
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = client.db(database)
// Enter your target collection as a parameter to this step
this.res = await db.collection(params.collection).insertOne({ name: "Luke Skywalker" })
await client.close()
},
})
Just don't understand why it won't connect. I can confirm the username and password aren't the problem.
I had a similar error message and it was a red herring.
The hostname needed to be the whole thing; cluster0.xx0xx.mongodb.net in my case, and I had the password wrong.
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
});
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've tried to follow this tutorial https://www.youtube.com/watch?v=VF38U2qd27Q, but to no avail.
I realised that the syntax in the video already obsolete for example connectWithUri to become connect.
but when I tried to connect to mongo using deno_mongo with the latest docs, it still not working.
import { MongoClient } from "https://deno.land/x/mongo#v0.20.1/mod.ts";
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
const client = new MongoClient();
client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");
Then I found another library denodb but again can't connect to mongodb:
import { Database } from 'https://deno.land/x/denodb/mod.ts';
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
this.db = new Database('mongo', {
uri: dbString,
database: mongoDB
});
the error message:
error: Uncaught AssertionError
deno | throw new AssertionError(msg);
deno | ^
deno | at assert (asserts.ts:152:11)
deno | at MongoClient.database (client.ts:48:5)
deno | at new connectDB (connectDB.ts:35:23)
which part is wrong?
Looking at the deno_mongo README on GitHub.
For a local database you should use
//Connecting to a Local Database
await client.connect("mongodb://localhost:27017");
And if you are connecting to Mongo Atlas Database (and probably any other remote database) you should use:
//Connecting to a Mongo Atlas Database
await client.connect({
db: "<db_name>",
tls: true,
servers: [
{
host: "<db_cluster_url>",
port: 27017,
},
],
credential: {
username: "<username>",
password: "<password>",
db: "<db_name>",
mechanism: "SCRAM-SHA-1",
},
});
FYI
If you are using Mongo Atlas make sure to split up the connection string you get from 'Connection Wizard' in the Mongo Atlas dashboard over 3 (or how many replicas you have) entries in the server array. Like this:
servers: [
{
host: this.dbUrl1, // e.g. <name-of-cluster>-00-00.fbnrc.mongodb.net
port: 27017,
},
{
host: this.dbUrl2, // e.g. <name-of-cluster>-00-01.fbnrc.mongodb.net
port: 27017,
},
{
host: this.dbUrl3, // e.g. <name-of-cluster>-00-02.fbnrc.mongodb.net
port: 27017,
}
]
You get the connection string by:
Click 'Clusters' under Data storage (left side of the screen)
Click 'Connect' button
Click 'Connect to Application'
Select Driver: 'Node.js' and Version: '2.2.12 or later'
Connection string is displayed below. The servers are listed in a comma separated manner like this:
...<name-of-cluster>-00-00.fbnrc.mongodb.net:27017,<name-of-cluster>-00-01.fbnrc.mongodb.net:27017,<name-of-cluster>-00-02.fbnrc.mongodb.net:27017...
FYI-2
Make sure the master replica is listed first in the server array. Because if you want to do insertions into the database the master replica should be targeted. For me this was the 2nd mongo url, therefore the following server array worked for me:
servers: [
{
host: this.dbUrl2,
port: 27017,
},
{
host: this.dbUrl1,
port: 27017,
},
{
host: this.dbUrl3,
port: 27017,
}
]
the below code is working for me.
import { DataTypes, Database, Model } from 'https://deno.land/x/denodb/mod.ts';
const db = new Database('mongo', {
host: 'mongodb://localhost:27017',
username: '',
password: '',
database: 'DBMYAPP',
});
console.log(db)
I also faced the same issue while updating deno_mongo to the latest version. Use await to resolve client.connect method
Try this:
import { MongoClient } from "https://deno.land/x/mongo#v0.20.1/mod.ts";
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
const client = new MongoClient();
await client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");
I had the same problem on windows 10, so try this
on your local mongodb:
await client.connect("mongodb://127.0.0.1:27017");
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
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