Digital Ocean MongoDB Connection Error - node.js

I use Nodejs with Mongodb connection, it works. I didn't not change anything in code . Now I can't connect to mongodb. When I try connect with Robomongo when I don't use ssh I can't connect
But when I try to connect with ssh I can connect. My connection is success.
I can't understand problem.
My nodejs mongo connection in in here:
MongoClient.connect('mongodb://username:password#ipadress/dbname', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(process.env.PORT || 5000, () => {
console.log('listening on 5000')
})
})
Thank you for help.

Your mongodb is not listening on the external interface but on localhost only so you can't connect directly to the 139.x.x.x IP.
However, if you use SSH it will first tunnel into the host and then connect locally so it works.

Related

Why does local Robo3t connect to a remote Mongo DB instance, but NodeJs fails with IP whitelist error?

I am having issues connecting to MongoDb running remotely, and the connection error response I am getting from the server is somewhat weird.
My network access whitelist is set to allow all (0.0.0.0/0). Hence, my local robo3t installation was able to connect. However, I could not connect from my NodeJs code. Error is: "MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist"
IP whitelist seems to be an unlikely error, given that my local robo3t client is able to connect remotely to the same remote Mongo Atlas instance, as IP whitelist is allow-all.
How do I debug this kind of thing, please?
UPDATE: this is how I connect to MongoDb. Works well on local, too.
try {
const connectionString =
process.env.APP_ENV == "test"
? await getInMemoryMongoDbAdapter()
: `mongodb://${process.env.MONGODB_HOSTNAME}:${process.env.MONGODB_PORT}/${process.env.CBT_DATABASE_NAME}`;
logger.info(`Connecting to MongoDB service: ${connectionString}`);
await mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
} catch (error) {
reject(error);
}
The logger line correctly shows: Connecting to MongoDB service: mongodb://<user>:<password>#cluster0-xxx.yyy.zzz.net:<port>/<database>
UPDATE 2:
My localhost also does not connect via this node app; whereas my robo3t (local MongoDb client) connects. I guess that means Heroku-specific issues can now be comfortably ruled out
A decade later, I found that for the connection parameters, I needed to supply the authSource and ssl options, as below:
{
useNewUrlParser: true,
useUnifiedTopology: true,
authSource: "admin",
ssl: true,
}
Neither one works without the other. Big shout-out to #darklightcode for all the insights he gave, leading me to dig deeper. Thanks man!

I am not able to connect Atlas MongoDB Cloud from a2hosting shared NodeJS hosting

var express = require("express");
var mongoose = require("mongoose");
const uri = "<mongodb atlas connection string...>";
var app = express();
var port = 3000;
app.get("/sam/", (req, res) => {
mongoose.Promise = global.Promise;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
},
(err) => {
if (!err) {
return res.status(200).send("I am Working");
}
else {
return res.status(200).send(err);
}
});
});
app.listen(3000, () => {
console.log("Server listening on port " + port);
});
Form local development environment, I am able to access and working fine.
Once I deployed to a2hosting Node JS Shared hosting, I am getting following error:
{"message":"Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/","reason":{"type":"ReplicaSetNoPrimary","setName":null,"maxSetVersion":null,"maxElectionId":null,"servers":{},"stale":false,"compatible":true,"compatibilityError":null,"logicalSessionTimeoutMinutes":null,"heartbeatFrequencyMS":10000,"localThresholdMS":15,"commonWireVersion":null}}
Also following is the Mongo DB Network Permission.
I am not able to connect Atlas Cloud MongoDB from A2hosting, for this I raised a ticket and provided port number and connection details.
They resolved my issue quickly, by opened all the requested and opened Atlas MongoDB related ports and confirmed they are opened firewall wise at this time.
Now I am able to connect Atlas Cloud MongoDB from my NodeJS Shared A2hosting hosting.
Note: For security reason, I remove 0.0.0.0/0 from Atlas Mongo DB Network Permission, and added my shared hosting IP address.
I hope this post will help lot of developers to deploy NodeJS and Atlas Cloud Mongo DB application.

Can't connect to MongoDB Atlas from CentOS using NodeJS

I've created a cluster on MongoDB Atlas and have successfully connected to it using Compass and also using Node running locally.
When I try to run the same code on my CentOS machine i get an ECONNREFUSEDerror. Here is my Node code
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://myuser:mypass#tablematic-0-z4nuk.gcp.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log("ERROR: " + err);
client.close();
});
myuser and mypass are replaced by my actual username and password here.
I've opened up server's firewall for ports 27015, 27016 and 27017.
Atlas is set up to accept connections from any incoming IP.
I really can't think of what might be causing it...
I've figured it out. It ended up being the cPanel Firewall, even though I've opened the ports through firewall-cmd, my cPanel was still bypassing that configuration with its own firewall.
I'm not 100% sure but my connection strings are usually like
mongodb://user:pass#host.app:27017/db_name

MongoDB network access

previously I didn't really understand networking. I want to still access the database with a different internet connection. I have added the mongodb atlas whitelist to my current ip or made it allow access from anywhere but I instead got an error. how do i finish this? thanks
this is my code to connect to the server
mongoose.connect(MONGODB_URI)
.then(result => {
console.log('CONNECTED!');
app.listen(3000);
})
.catch(err => console.log(err));
here this error message
`D:\nodeJsApp\MyApp\node_modules\mongodb\lib\topologies\replset.js:368
throw err;
^
Error: Error connecting to db: failed to connect to server `

NodeJs text file writing

I am trying to write a text file from NodeJs. I have server running on my laptop. Currently, i am running client on my laptop and it works fine. But if i run same NodeJs client on Linux running on raspberrypi, it doesn't write on file or neither it gives any error.
I have the following code for client
var ioC = require('socket.io-client'),
ioClient = ioC.connect('http://localhost:4000'),
fs = require('fs'),
os = require('os');
ioClient.on('connect', function () { console.log("socket connected"); });
ioClient.on('ChangeState', function(msg){
console.log(msg);
fs.writeFile('server.txt', JSON.stringify(msg), function (err){
if (err) return console.log(err);
});
});
Can anybody please help me what can be the issue with this?
You are connecting to localhost which won't work if the client is on a different machine. You need to change the server to listen to the ip address your server has in your network, and also need to let your client connect to this ip. You can get the ip by running ifconfig in your terminal. Then (depending on wireless or wired connection) look for something like (usually the last paragraph):
and create the server on this ip. E.g.
192.168.178.30:4000
and connect to the same address from your client.
To find your ip on windows, refer to this guide

Resources