connecting to remote mongodb with nodejs - javascript

i have a remote mongo server and i want to connect to that with nodejs . i tried connecting directly with mongo shell and it was ok ... but i cant connect to that mongodb server in nodejs ..
the mongo command for connection :
mongo --host 192.168.10.33 --port 27017 -u mohammad -p "mypassw#12" --authenticationDatabase=access
i only want to convert that command into nodejs connection config..
something like:
uri = mongodb://mohammad:mypassw#12#192.168.10.33:27017/"

The URI should be encoded
uri = "mongodb://mohammad:mypassw%4012#192.168.10.33:27017/access"
mongo.connect(uri, { useNewUrlParser: true }, (err, db) => {});

Connecting to a remote Mongo can sometimes be tricky , mongoose can help a great lot with connecting to your remote db . The code below should be able to do the trick and connect .
const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
const uri = "mongodb+srv://user:pass#clusterName.d4zrk.mongodb.net/databaseName?retryWrites=true&w=majority";
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log('Database Connection Established!')
})

I guess the issue might be with your password, it looks like to contains a special character that is used by the mongodb driver to separate the credentials from the host:
mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
If you have a # in your password, you have to apply an percent encoding it by adding a % character.
Here is the list of character to encode according to mongodb driver documentation: : / ? # [ ] #

Related

How to connect nodejs redis client to redis cloud server?

const redis = require('redis');
const client = redis.createClient({
host: 'redis-19606.redislabs.com',
port: 19606,
password: 'password'
});
client.on('ready', () => {
console.log('redis is connected');
});
client.on('error', (err) => {
console.log('redis is disconnected: ', err);
});
(async () => {
try {
await client.connect();
} catch (error) {
console.error('error while connecting redis', error);
}
})();
This somehow does not seem to work. What am I doing wrong? It keeps connecting to 127.0.0.1:6379 which is the default config instead of what I am passing. This is only happening with nodejs client of redis. go-redis the golang client for redis is working flawlessly.
Just a guess, but which Node Redis version do you use? I had difficulties upgrading myself. The configuration of the client has changed since version 4.x.x. Since version 4.x.x you have to use a confiuration according to Client Configuration. Therefore use
const client = redis.createClient({
socket: {
host: 'redis-19606.redislabs.com',
port: 19606,
}
});
or use a URL
const client = redis.createClient({
url: "redis://redis-19606.redislabs.com:19606"
});
Your client configuration matches the Node Redis version 3.x.x but not 4.x.x. Please see Redis NPM v3.1.2 and Redis NPM v4.0.1 for details.
you should maintain this format of Redis connecting string:
redis://:YOUR_PASSWORD#YOUR_ENDPOINT:YOUR_PORT
What version of redis are you using?
Do not explicitly conect to redis by writing "client.connect()" but
instead use this after setting host, port and password:
redisClient.on("connect", () => {})
and then you can use redisClient variable to get and set values.
Also if you're trying to connect to a redislabs server then I think your host name might be incorrect and double check your host from redislabs.
Try this new Redis("redis://username:authpassword#127.0.0.1:6380/4");
Check the documentation Link

MongoDB/Mongoose Connection Error when Dbname is used in the connection string

A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.
The connection can be established when we use
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri)
Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)
and also tried
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.
Why is it unable to make the connection and how can we solve this problem?
Update
Found the solution to be
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })
Why must the dbname be passed as an option instead of including it in the connection string?
This has worked for me, thanks.
var result = await mongoose.connect('mongodb://root:example#localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})
Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)
Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.

Why is Sequelize not authenticating against my MS Sql Database?

When attempting to connect to my local SQL Server instance I am receiving an error stating Authentication failed for login. However I am able to login directly to the server in SQL using the provided login.
Here is my code that is attempting to connect to the server.
var Sequelize = require('sequelize');
const sequelize = new Sequelize('GraphQLTests', 'gql', 'Password1', {
dialect: 'mssql',
host:'localhost'
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
I have printed to the console in the Sequelize code to verify that the correct credentials are getting passed but still receive this error.
name: 'SequelizeAccessDeniedError',
parent:
{ ConnectionError: Login failed for user ''.}
Please let me know if there is any other info I can provide.
try this
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});
sequelize.authenticate().then((err) => {
console.log('Connection successful', err);
})
.catch((err) => {
console.log('Unable to connect to database', err);
});
Try this link as reference Connecting to MSSQL server with Sequelize
This is what worked for me, where I have put the server details in an YAML file. (this way, you can switch servers on the fly).
this is the sequelize code
//get the configure from the YAML file
const YAML = await fs.readFile(process.env.SEQUELIZE_CONNECT,'utf8');
//load the database parameters into our system
const params = jsyaml.safeLoad(YAML, 'utf8');
//initiate our database server details to connect to our underlying database system
//as described in the YAML file.
sequlz = new Sequelize(params.dbname, params.username, params.password, params.params);
Here is how my YAML file looks. (I have left my code comments as it is)
#this should work to whatever you are using anywhere.
#as per the YAML file title, I am using a MS SQL server hosted on Azure.
# you can edit values. as per your requirement.
# check the dialect help file of your server on the sequelize documentation
# https://sequelize.org/v5/file/lib/dialects/mssql/connection-manager.js.html
#change the values as per your server.
dbname: databasenamehere
username: usernamehere
password: passwordhere
params:
host: servernamehere.database.windows.net
dialect: mssql
dialectOptions:
{
options: {
encrypt: true,
requestTimeout: 10000
}
}
So, that worked for me. (I have remixed answers from above post, and also from the textbook and multiple online resources I was referring).
Note : The server is running on Azure with the Firewall IP address set to ALL IP address.

node.js - Can't connect to MYSQL database with Sequelize

I'm starting at Node.js and i'm trying to make a simple connection with Sequelize based on its documentation (http://docs.sequelizejs.com/manual/installation/getting-started.html#installation).
Here my db.js file :
const Sequelize = require('sequelize')
const db = new Sequelize('chat','root','root',{
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
When executing this code, I have no success nor error message, just a message indicating 'String base operators deprecated' but nothing important i think.
I tried changing localhost to 127.0.0.1, remove port number and multiples thread but i'm stucked here...
Tested your code and all seemed to work fine, it connected successfully to the database instance I have running.
You might want to ensure mysql2 package is installed. Also check that the database chat has been created in MySQL workbench, and ensure the password is correct.

How do I query the DB when the dbPath is not default? MongoDB

Previously I had been connecting to my db like this:
const db = 'mongodb://localhost/dbname';
mongoose.connect(db, {
useMongoClient: true
});
After following along with a tutorial, I decided to change where my logs and db is stored. I changed my connection to:
const db = 'mongodb://localhost:5000';
mongoose.connect(db, {
useMongoClient: true
});
And I created a mongod.conf:
# where to write logging data
systemLog:
destination: file
logAppend: true
path: /Users/matt/mongodb/sampledb/logs/mongod.log
# Where and how to store data
storage:
dbPath: /Users/matt/mongodb/sampledb/data/db
journal:
enabled: true
# network interfaces
net:
port: 5000
bindIp: 127.0.0.1
Now when I "show dbs" from the mongo shell, I am not sure "use" the db to query it. I figure I am missing a step somewhere.
My issue was my that I was using a non-default port. So instead of starting the mongo shell with:
mongo
I needed to start it with:
mongo --port 5000
I also added a name to my db in the connection:
mongoose.connect('mongodb://localhost:5000:/dbname', {
useMongoClient: true
});

Categories