Cant connect to MongoDb - node.js

so this is my code, I watched a lot of videos how to connect mongo db to node and I tried every possible way but it doesnot connect. What's wrong with my code??? also I downloaded every important thing

Your Connection URL is without a port number, add the port number to the URL
mongodb://localhost:27017/subscribers
MongoDB - default port number is 27017
https://docs.mongodb.com/manual/reference/default-mongodb-port/
https://mongoosejs.com/docs/connections.html#connections
You can connect to MongoDB with the mongoose.connect() method.
mongoose.connect('mongodb://localhost:27017/myDB', {useNewUrlParser:
true}); This is the minimum needed to connect the myapp database
running locally on the default port (27017). If connecting fails on
your machine, try using 127.0.0.1 instead of localhost.
You can also specify several more parameters in the uri:

Related

NodeJS MongoDB API in Docker Container can't connect to Database running on Host

I have a MongoDB Database set up on my host server and a docker container running on that host with a NodeJS application. In that application, I try to connect to the Database on the host but the request always times out.
I set the network to "host" and used the adress "host.docker.internal". I also tried installing mongodb-shell and it actually works! So basically I can connect to the database with the shell in the container but not with the MongoDB NodeJS API.
Code of the NodeJS application:
const mongodb = require('mongodb');
mongodb.MongoClient.connect("mongodb://host.docker.internal:27017/");
using mongo mongodb://host.docker.internal:27017/ in the shell works and I connect correctly.
I finally found out the issue.
I had to bind it to the correct IPs / in my config I used the argument --bind_ip_all.
Thanks a lot for the help!

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!

MongoNetworkError: failed to connect to server on first connect [MongoNetworkError: connect ECONNREFUSED ]

I got this error as soon as I tried to run the nodejs app in Godaddy shared hosting cPanel terminal while trying to connect to mongo atlas cluster.
I have whitelisted both the IP of the server and set access to all still not working.
Same code is working fine in local system
My node.js code goes as:
Here is the DB url
If anyone has experienced this issue and able to solve it, then please provide me the solution. Thanks :) in advance.
I am pretty sure, that you IP is a provider's IP, not you own. According to a console, problem is in whitelisting.
So make sure that you are enable in your driver, all connections options, like this:
(if you are using mongoose)
connect(`mongodb+srv://${process.env.login}:${process.env.password}#${process.env.hostname}/${process.env.auth_db}`, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
w: "majority",
family: 4
});
And then white-list every IP in your Atlas console, like that:

What does this 27017 stands for in the following code?

var employeeProvider = new EmployeeProvider('localhost', 27017);
What is this 27017?
This code is written in Node.js.
That's most likely a port number. In this case, it's probably specifying the connection info for a MongoDB server (since 27017 is the default port that Mongo uses).
In itself, the code is just invoking the EmployeeProvider function with two arguments.. One string 'localhost', and one number 27017. The code can't mean anything else if you don't know what is the code behind that function. That said, it looks like the function opens a MongoDB connection on the default port (27017) to the mongodb server on the local machine.

Can't access MongoDB from subdomain on same server

I am running NginX, Node and Mongodb. And it seems that I can't acces the same database from a second app I am running. For example, I don't get anything back when I do:
collection.findOne({
name: someName
}, function(err, results){
// Returns no errors or results. Just stops working.
});
I can access the database perfectly fine from my first app, but not the second one.
This is the code I use to connect to the database in both apps.
Server = require('mongodb').Server,
Db = require('mongodb').Db,
db = new Db('database', new Server('localhost', 27017, { auto_reconnect: true }), { w: true });
Anyone know what the problem might be?
Edit: Does it have something to do with the subdomain or ports? Too many connections?
Edit 2 (more info):
I run mongodb with service mongodb start.
In my /etc/mongodb.conf I have bind_ip = 127.0.0.1 and dbpath=/var/lib/mongodb (rest is default)
In both my apps I run the same code to establish a connection to the database, but only the first one works (I know that because I am able to retrieve information from the database in my first app).
The apps are running on different ports. The first one is running on port 1337 and the second one runs on 3000.
You are using 'localhost' as the host name to connect to this server.
This means you will only be able to connect from the same machine that mongod is running on with that hostname.
Unless all your apps run on the same server as mongod you will need to change your connect code to use the actual hostname of the mongod server.

Resources