Why can I not connect to the mongoose server - node.js

I have implemented the code below in a db.js file to require mongoose and connect to the mongoose server. The code is below which is in a db.js file
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/CaribbeanDb';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function (){
console.log('Mongoose connected to ' + dbUEI);
});
mongoose.connection.on('error', function (err){
console.log('Mongoose connection error:' + err);
});
mongoose.connection.on('disconnected', function (){
console.log('Mongoose disconnected:');
});
I will get this error when I try to connect to mongoose
node:16880) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Mongoose disconnected:
Mongoose connection error:MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
So I changed the second line of code that is in the db.js file to the code below
mongoose.connect('mongodb://localhost:27017/CaribbeanDb', {useNewUrlParser: true})
after the changes... I now get this error below
Mongoose connection error:MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
I have tried to do further research to solve the error. I came across some commands which are below. to input into git terminal to solve the issue, but the commands are not found within the terminal.
$ sudo rm /data/db/mongod.lock
$ sudo mongod --dbpath /data/db/ --repair
$ sudo mongod --dbpath /data/db/ --journal
Any suggestions .. as I am running out of ideas where I am going wrong?

Do you have MongoDB installed on your machine?
Mongoose is an ORM, while MongoDB is the actual database which makes it a dependency for Mongoose.
If you're on macOS, you can run:
mongo -version
If it spits back that you do not have it, install with Homebrew:
brew install mongo
sudo mkdir -p /data/db
sudo chown -R `id -un` /data/db
Start the MongoDB daemon:
mongod

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

mongoose not connecting to localhost

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.

MongoError: failed to connect to server [localhost:27017]

This is my db.js:
import mongoose from 'mongoose';
export default () => {
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/meetupapp');
mongoose.connection
.once('open', () => console.log('Mongodb running'))
.on('error', err => console.error(err));
};
and this is the error message: MongoError: failed to connect to server [localhost:27017] on first connect]
name: 'MongoError
I've installed mongodb!
Verify your mongodb engine is running or not
WINDOWS
1.) Open command prompt
2.) Type mongo
if it works that means mongod is running or else you have to start it manually
COMMAND
mongod --dbpath [path-of-your-database]
create folder where you want to store the database and assign that folderpath in --dbpath
Ex "c:/mongo/db/"
and then try mongo command and it will work..
LINUX
COMMAND
1.) sudo service mongod start
MAC
After installing mongodb
COMMAND
1.) export PATH=<mongodb-install-directory>/bin:$PATH [Setting the environment variable]
2.) mkdir -p /data/db [creating directory for data to store]
3.) mongod --dbpath [path-of-your-database]

connect ECONNREFUSED 127.0.0.1:27017'

I have that code:
var express = require('express'),
stylus = require('stylus'),
logger = require('morgan'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
function compile(str, path){
return stylus(str).set('filename', path);
}
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(stylus.middleware(
{
src: __dirname + '/public',
compile: compile
}
));
app.use(express.static(__dirname + '/public'));
mongoose.connect('mongodb://localhost/multivision');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error..'));
db.once('open', function callback(){
console.log('multivision db opened');
});
app.get('/partials/:partialPath', function(req, res){
res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req, res) {
res.render('index');
});
var port = 3131;
app.listen(port);
console.log('Listening on port ' + port + '...');
but when I'm trying nodemon server.js it throws an error:
connection error.. { [MongoError: connect ECONNREFUSED
127.0.0.1:27017] name: 'MongoError' message: 'connect ECONNREFUSED 127.0.0.1:27017' }
how can I improve that? I've already installed mongoose using npm install mongoose --save in my directory
Yeah there are dozens question like this but none of these helped me.. I'm new at nodejs and probably missing something
I was also facing the same issue, when I was executing node server on my project directory. For me the MongoDB service was not started, that makes this issue.
So I had to run services.msc and activated the service.
After that I was able to run my command.
D:\SVenu\MyApp>node server
Saving User
App is listening on port: 3000
Already Exist
Already Exist
Already Exist
Already Exist
Done save
run services.msc and activate the Mongodb service.
Now Mongodb will connect
the status of the Mongodb indicated as Running
Your mongodb service is probably down.
Run sudo service mongod start to start the daemon process
I was having the same problem, and found that it was a mongod issue.(I am running Ubuntu 16.04). Looking through the errors there was a directory missing. After adding the directory, I needed to change permissions, and finally, set the mongod service to start at boot.
$ sudo mkdir -p /data/db
$ sudo chown -R $USER /data/db
$ sudo systemctl enable mongod.service
I know this issue is old, but i came across a similar issue and the above solutions did not work for me, I'm using Ubuntu 20.04 LTS.
What i did to make it work was just running mongo service using this command:
$ mongod
Then everything worked fine
If you're in windows and you had this issue,
just go the installer exe app for the mongodb
and click "Repair"
this works for me
try this:
mongod.exe --dbpath c:\data\db
c:\data\db is the place where you put your db.
and when you see something like this :
2016-08-18T10:22:31.020+0800 I CONTROL [main] Hotfix KB2731284 or later update is not installed, will zero-out data files
2016-08-18T10:22:31.022+0800 I CONTROL [initandlisten] MongoDB starting : pid=4356 port=27017 dbpath=c:\data\db 64-bit host=sevencai-PC0
2016-08-18T10:22:31.022+0800 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-08-18T10:22:31.023+0800 I CONTROL [initandlisten] db version v3.2.8
2016-08-18T10:22:31.023+0800 I CONTROL [initandlisten] git version: ed70e33130c977bda0024c125b56d159573dbaf0
......
and then node yourserver.js
maybe everything will be fine!
Follow as below:
=> run services.msc and start mondodb server
and save the file in node project, you can see the server connected!!
In Most of the case you will get the error bcz the service MongoDB Database Server (MongoDB) Might be stopped.
Just start the service to be connected with DB
it's doesn't work as localhost but IP address works 127.0.0.1 and solves this problem:
// .connect("mongodb://localhost:27017/lofydb")
const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/lofydb")
// .connect("mongodb://127.0.0.1:27017")
.then(() => {
console.log("Connected to Database");
})
.catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
please check the MongoDB service is active and running.
Refer the running services
If it is running and available on MongoDB compass or on MongoDB shell and if you are working with node version >17.0.0 or so it will give error.
So plz change to the stable version of node.
Make sure MongdoDB is running
To run MongoDB as a macOS service, run:
brew services start mongodb-community#5.0
And when you see:
==> Successfully started mongodb-community (label:
homebrew.mxcl.mongodb-commu
OR type on command line, to check the mongo service.
mongod
After run service, You can easily connect with mongdoDB localhost or remote connection.
I had the same issue and it had to do with the fact that my MongoDB service wasn't running locally. Make sure you followed all the correct installation steps for whatever OS you are trying to run MongoDB service here: https://www.mongodb.com/docs/manual/administration/install-community/
Then follow the respective guide for the running the service under "Run MongoDB Community Edition". So for example, for macOS you would do
brew services start mongodb-community#6.0
if you wanted to run as a macOS service, or
mongod --config /opt/homebrew/etc/mongod.conf --fork
if you wanted to run manually as a background service on Apple M1 processor. The same page I shared above also has commands you can run for verifying if your MongoDB process is running.
Step 1: open conf file to edit.
sudo vim /etc/mongod.conf
Step 2: find port and change it.
net: port: 27017 -> default port before any change
After changing port, my issue solved :

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.

Resources