mongoose not connecting to localhost - node.js

I seem to have issues when trying to create a mongoose connection. I am following a book published in 2014 so my immediate response was to check the mongoose docs but they agree that the book gives the correct format. Below is my connection:
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
As soon as I add these lines, I get the following error:
Mongoose connection error: mongodb://127.0.0.1/Loc8r
(node:743) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:743) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If I remove the connection, I have no errors...but that would defeat the purpose of trying to connect to a DB. I also tried substituting localhost in the URI for 127.0.0.1 which is known to solve some issues but I had no luck there either. I am running the localhost on a simple $nodemon command via terminal and nothing else.
Useful info:
MongoDB v3.6.3
Mongoose v5.0.10
Express v4.15.5
Node v8.9.4
Help would be appreciated.
Thanks.

try this way
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});

You are going on the right path but you forgot to put the port on which MongoDB runs,
MongoDB runs on the port 27017
Do not forget to start MongoDB server, If you are on mac open terminal and enter mongod and it will start your MongoDB server then run your code it will work fine.
var dbURI = 'mongodb://localhost:27017/Loc8r';
mongoose.connect(dbURI);
mongoose.connection.on("connected", () => {
console.log("Connected to database");
});
mongoose.connection.on("error", (err) => {
console.log("Database error:" + err);
});

I apologise for this as I was able to find the solution myself but I guess this may help others some day.
The fault lay with the fact that I only installed MongoDB via Homebrew and I stopped as soon as MongoDB was literally "installed" and considered MongoDB to be "installed". I went back to look at how MongoDB should properly be installed and I noticed that I did not make the directory /data/db and give it its permissions which was an important step.
Once I did this, I ran mongod globally, and nodemon on a separate terminal, locally at the root of the app and it worked completely fine and got a successful message in the console. Every time I tried to connect, it was searching for /data/db which it obviously could not find as I had not made it. But I would not have came to this conclusion if Nikhil had not mentioned running mongod.
To summarise, ensure you follow all installing steps in future.

Related

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

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.

Localhost run Node.js app can't connect to mongolabs

I'm pretty new to Mongo and Node. I set up a test account on mongolabs and created a new admin user. Then in my localhost I required mongoose and used.
mongoose.connect('mongodb://admin:password#ds045475.mongolab.com:45475/nodelearn', function(err){
if (err) console.log(err);
});
however, it keeps throwing the error: [MongoError, connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONN REFUSED'. I have the mongolab address right, and I have mongoose imported. I'm not sure what the problem is.

Connection to MongoDb failed

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.

Auth failed error when specifying database

I'm trying to connect to a mongodb from my web application. However, I get an auth failed error from mongo when I specify the database I want to connect to. If I do not specify the db, then to connection is successful.
I have checked the spelling and if the database exits with the mongo command line show dbs
var dbURI = 'mongodb://root:pwd#localhost:27017/dbname';
mongoose.connect(dbURI, function(err) {
if (err) throw err;
});
C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\base.js:245
throw message;
^
MongoError: auth failed
at Object.toError (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\utils.js:114:11)
at C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\db.js:1130:31
at C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\db.js:1847:9
at Server.Base._callHandler (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\base.js:445:41)
at C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:478:18
at MongoReply.parseBody (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\responses\mongo_reply.js:68:5)
at null.<anonymous> (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:436:20)
at emit (events.js:95:17)
at null.<anonymous> (C:\Users\David\Documents\Bitbucket\productWebsite\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:201:13)
at emit (events.js:98:17)
I'm using Bitnami Mean stack for Windows
Can someone tell me what I am forgetting?
It matters which database you try to authenticate to. Authenticate to the database where the user was created. You can switch to using other databases once authenticated.
You might want to do something like this...
var opt = {
user: config.username,
pass: config.password,
auth: {
authdb: 'admin'
}
};
var connection = mongoose.createConnection(config.database.host, 'mydatabase', config.database.port, opt);
'authdb' option is the database you created the user under.
In my experience, I found that the reason might be the version difference between the mongoose and mongoDB. In my package.json the mongoose version is the 3.8.5 and my mongoDB version is 3.0.4, I changed the mongoose version 3.8.5 to 4.1.5 and ran the command:
npm update
and ran the app, that worked for me.

Resources