Mongo DB - UnhandledPromiseRejectionWarning: Error - mongodb

I am testing my app on localhost and using mongdb to connect to a database. I was receiving this error:
UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:27017
I figured out how to reconnect by going into Services and manually starting MongoDB.
However, after researching, I found that my code is not handling the error catching properly. I am not sure how to restructure my code (using .catch() I believe?) to fix this.
Would appreciate any suggestions to help fix and will be great to be able to learn how to do so.
Thanks in advance!
const express = require('express');
const validate = require('./validate.js');
const mongoose = require('mongoose');
const moviesRouter = require('./routes/movies.js');
const app = express();
const PORT = process.env.PORT || 3000;
const DATABASE_URL = process.env.DATABASE_URL ||
'mongodb://localhost/movies';
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,
useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', error => console.error(error));
db.once('open', () => console.log('Connected to Database'));
app.use(express.json());
app.use('/movies', moviesRouter);
app.listen(PORT, () => console.log(`listening on port: ${PORT}`));

As you suggest, using a catch statement would be one way to handle the connection error:
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,
useUnifiedTopology: true }).catch(error => console.error(error));
If an error happens during connection the error will be handled and returned. More info here: https://mongoosejs.com/docs/connections.html#error-handling

Related

I am trying to connect mongodb ATLAS

[nodemon] restarting due to changes...
[nodemon] starting node server.js
Server is running on port: ${port}
D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\connection_string.js:290
throw new error_1.MongoParseError(${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\connection_string.js:290:15)
at new MongoClient (D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\mongo_client.js:64:63)
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\connection.js:801:16
at new Promise ()
at Connection.openUri (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\connection.js:798:19)
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\index.js:380:10
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise ()
at promiseOrCallback (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\index.js:1225:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.7.0
[nodemon] app crashed - waiting for file changes before starting...
And the code is
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express ();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', ()=>{
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log('Server is running on port: ${port}')
});
process.on('warning', e => console.warn(e.stack));```
According to the mongoose docs
useCreateIndex isn't an option to mongooose.connect()

how to connect to mongodb from express?

Tried to connect To mongodb, it says connection not found. can someone point out what error I have made in code, is there any problem in db connect URI
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
const db =
"mongodb+srv://<sumit>:<sumit>#bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
console.log(db);
mongoose
.connect(db)
.then(() => {
console.log("connection successful");
})
.catch((err) => console.log(err));
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
This is a snippet from my own application it works there
mongoose.connect(dbUrl).then((dbo)=>{
console.log("DB connected")
},(err)=>{
console.log("error")
});
I have connected like this your then is missing a variable tell me if this dosnt work
Finally found a solution.
Thanks for the help #ahmed ali.
In db uri, username and password should be written without angular brackets and replace the first database with your database name created.
Write down the username and password example:
monggoose.connect('mongodb+srv://name:password#cluster0.cjjucgj.mongodb.net/?retryWrites=true&w=majority')

Cannot connect to MongoDB - Authentication Failed

Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!

Getting MongoParseError: Invalid message size: 1347703880, max allowed: 67108864

I am building a RESTful BLogAPP where my stack is MEN
while connecting to mongo server i am getting this error
These were working But this happened
My Mongo file code
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = "mongodb://localhost/127.0.0.1:27017/Blog";
mongoose.connect(url ,{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", url);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
module.exports = mongoose;
My app.js
const mongoose = require("./server/mongoose");
It was resolved for me after remove server port from connection string. Replace mongodb connection string From
const url = "mongodb://localhost:27017/Blog";
To
const url = "mongodb://localhost/Blog";
I got the same error message and I've finally solved it. Try to leave it like this:
const url = "mongodb://localhost:27017/Blog";
I too got the same error while accessing MongoDB via mongoose.
The URI I set was MONGO_URI=mongodb://localhost:3000/myDB.
The port was wrong.
I solved it by correcting the Mongo URI.
MONGO_URI=mongodb://localhost:27017/myDB.

Connecting to the mongodb

I'm new in the MEAN developing, I'm developing a simple app, and for my first step I'm trying to connect to my mongodb, so I installed node, express, morgan,mongodb, mongoose.
So here is my code in index.js:
const express = require('express');
const morgan = require('morgan');
const app = express();
const { MongoClient } = require('./database');
// Settings
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
// Routes
// Starting the server
app.listen(app.get('port'), () => {
console.log('server on port', app.get('port'));
});
and then the code on my database.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.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("horrorrrrrr");
// perform actions on the collection object
client.close();
});
module.exports = MongoClient;
I also try this code that is on the mongodb page to connect to the application:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Of course I change the password to the real one. Please keep in my today it's my first time I touch mongodb and also the MEAN full stack, and I spent too many hours stuck in this connection.
this is the error I get:
(node:5284) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
EDIT
#iLiA thanks for your reply ! I tried your code and ain't working, I will show you how I did it with the real password :
const url = 'mongodb+srv://duke:password#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is not a problem with ${err.message}`);
process.exit(-1)
})
module.exports = mongoose;
and the error is :
there is not a problem with Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Kind regards,
I am confused about why do you downloaded both mongodb and mongoose but here is mongoose solution
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is a problem with ${err.message}`);
process.exit(-1)
})
EDIT:
As it seems you forgot to whitelist your IP address in mongo atlas.