Connection to MongoDb failed - node.js

I was trying to connect my mongodb with node server using command prompt.
I started mongodb my mongod --dbpath E:\node start\node\data
Then I installed mongodb dependencies using npm install mongodb
I added some code into my app.js which is described below :
app.js
var mongodb = require('mongodb'); //acquiring mongodb native drivers
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:7000/myDatabase'; //connection url
mongoClient.connect(url, function(err,db){
if(err){
console.log('Unable to connect to mongodb server. Error :' , err);
}
else{
console.log('Connection established to', url);
db.close();
}
});
when I ran app.js in command prompt, following error occured :
Unable to connect to mongodb server. Error :{[ MongoError : connect ECONNREFUSED] name : 'MongoError' , message: 'connect ECONNREFUSED' }
I cannot understand what the problem is and what should I do next.

MongoDB usually runs on port 27017, but you're trying to connect to port 7000. Try changing your url variable.
var url = 'mongodb://localhost:27017/myDatabase';

You know mongoDB has their default port no 27017.
And You have written 7000.
So Try to Change port no to 27017.
ok !!!!!!!

The error says you do not have mongodb running. You should check if your mongodb is running or not. If its running then you should check on what port it is running on.
The default port for mongodb is 27017. If you have not configured your mongodb to run on port 7000 then changing var url = 'mongodb://localhost:7000/myDatabase'; to var url = 'mongodb://localhost:27017/myDatabase'; will work for you.

Related

Unable to connect to remote redis host [nodeJS]

const redis = require('redis');
require('dotenv').config();
console.log(process.env.redisHost, ':', process.env.redisPort);
const redisClient = redis.createClient({
host: process.env.redisHost,
port: process.env.redisPort,
password: process.env.redisKey
});
redisClient.connect();
redisClient.on('error', err => console.log('Redis error: ', err.message));
redisClient.on('connect', () => console.log('Connected to redis server'));
module.exports = redisClient;
I tried this sample from redis docs but still I'm getting an error stating:
Redis error: connect ECONNREFUSED 127.0.0.1:6379
I logged the environment host and port variables to the console and I got the remote host ipv4 address, but still the client is trying to connect to localhost instead of remote host (I purposely uninstalled redis from my local device to check if the client is working as it is supposed to). I also confirmed that the remote redis host is working perfectly.
I also tried different methods like :
https://cloud.google.com/community/tutorials/nodejs-redis-on-appengine
redis.createClient(port, host, {auth_pass: password});
But still, I got the same error.
I am able to connect to the redis host via commandline:
redis-cli.exe -h XX.XX.XX.XXX -a Password
XX.XX.XX.XXX:6379> set name dhruv
OK
XX.XX.XX.XXX:6379> get name
"dhruv"
XX.XX.XX.XXX:6379> exit
I'm trying to use redis on nodejs for the first time, so don't have a proper idea but I think I am doing everything right.
Any solution/workaround will be helpful :D
It worked with this code:
const url = `redis://${process.env.redisHost}:${process.env.redisPort}`;
const redisClient = redis.createClient({
url,
password: process.env.redisKey
});
redisClient.connect();
can you check if in the destination the port is reachable. it maybe the firewall block your access

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 in mongoose6.1.13

I'm using NodeJS with MongoDB using MongoDB package. When I run mongod command it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient does not work and gives an error when I run node index.js code.
The error is given below in the picture.
I have installed mongo DB 5.0.5, mongoose package 6.1.13 and my code is-
// getting-started.js
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost:27017/test');
}
I'm able to connect the database by console log and windows power shell but not by the node.js
Error description

Local mongodb Node.js server succesfully authenticates then ends connections after a few seconds

I am trying to run an Express server that would communicate with a local MongoDB instance. Everything runs on Ubuntu 18.04.5 on DigitalOcean.
I managed to set up the database, the authentication is made, but then after a few seconds the connection closes due to some mongodb dependencies (I think).
This is how I make the connection:
const httpsServer = https.createServer(credentials, app);
const mongooseConnection = mongoose
.createConnection(
`mongodb://user:pass#127.0.0.1:27017/Database?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
mongooseConnection.on('error', console.error.bind(console, 'Connection error: '));
mongooseConnection.once('open', () => {
console.log("Connected to the DB");
httpsServer.listen(securePort, () => {
console.log(`Secure Express server listening on port ${securePort}`);
});
});
Node console:
Mongod:
Couldn't find much about this error. Most of what I've found is related to the MongoDB Atlas cloud service, but this is a local MongoDB instance. The common solution for when the connection closes like this seems to be whitelisting the IP. I think this is not the case as everything is local and I have nothing to do with the Atlas/Cluster.
I tried removing the node modules and updating them. I tried disabling cors and helmet. I'm stuck

Can't establish SSL connection to MongoDB from NodeJS program

I am trying to connect a mongod instance from NodeJS program using Mongoose that configured with SSL connection but I'm getting the following error on the mongod console: "Error receiving request from client: SSLHandshakeFailed: The server is configured to only allow SSL connections."
The mongod instance is initiated as follow:
mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem
I tried to use MongoClient instead of mongoose but nothing new happened.
This is my piece of code:
if(envConfig.config.db.tls === true){
let certFile = [fs.readFileSync("C:/PATH/TO/Key/mongoDB.pem")];
mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
server:{
sslValidate: true,
sslCA: certFile
}
});
}else{
mongoose.connect(`mongodb://${dbUrl}`,options);
}
It is not something about the PEM file because when I start the mongod as I wrote and use SSL connection with MongoDB Compass using the same PEM file from the code - it works.
MongoDB version: 3.6.0
Mongoose version: 4.13.6
Happy if someone will guide me what am I doing wrong.
I think you should refer to the question Mongoose SSL, connection not accepted
You should specify {server: {ssl: true} parameter and I think your problem will be solved
If you initiate MongoDB daemon with private key and certificate
mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem --sslCAFile C:/Users/MyUsername/Path/mongodb.crt
You can connect from Node JS like
if(envConfig.config.db.tls === true){
let key = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.pem");
let crt = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.crt");
mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
server:{
"sslValidate" :true
"sslKey": key,
"sslCert": crt, // if you have one certificate you can use `sslCert` parameter
}
});
}else{
mongoose.connect(`mongodb://${dbUrl}`,options);
}
More detail explanation of SSL connection via Node JS you can go here
Solved!
Problem was using express-session middelware and trying to connect the DB with incorrect connection string, that what caused the problem.

Authentication problem with connecting to mongodb Atlas

What I want to accomplish is probably the simplest thing ever. I just want to connect to mongodb atlas free tier M0 in nodejs using mongodb driver. I already have created a free account and cluster.
Here is my simple code:
const mongoclient = require('mongodb').MongoClient;
const URI = 'mongodb+srv://mohammed:mypassword#lebran-0qf7m.gcp.mongodb.net/test?retryWrites=true';
mongoclient.connect(URI, { useNewUrlParser: true }, (err, client) => {
if(err) throw err;
console.log('mongodb connected');
db = client.db('mern');
})
Here is what happens when I run the file:
Mohammeds-MacBook-Pro:mern ahmed$ node server.js
/Users/ahmed/Projects/mern/server.js:13
if(err) throw err;
^
Error: queryTxt ESERVFAIL lebran-0qf7m.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:199:19)
I also tried mongo shell with the following command:
mongo "mongodb+srv://lebran-0qf7m.gcp.mongodb.net/mern" --username mohammed
here is the output I get:
MongoDB shell version v4.0.6
Enter password:
connecting to: mongodb://lebran-shard-00-00-0qf7m.gcp.mongodb.net.:27017,lebran-shard-00-01-0qf7m.gcp.mongodb.net.:27017,lebran-shard-00-02-0qf7m.gcp.mongodb.net.:27017/mern?gssapiServiceName=mongodb&ssl=true
2019-02-20T22:48:57.232+0300 E QUERY [js] Error: Authentication failed. :
connect#src/mongo/shell/mongo.js:343:13
#(connect):1:6
exception: connect failed
I am sure I enter my password right. I have changed several ones and none of them work. I have my IP listed as white list. I also have an admin account. All the prerequisites I can think of.
I am able to connect to the local server but not to the Atlas. This really beginning to drive me crazy.
Any help is greatly appreciated...
**UPDATE:
I just deployed my app to heroku and you know what? It connects!! I could not get it to connect using my computer though. So probably it has to do something with my location or my connection, probably the location.

Resources