I have seen this issue published in a few places however I still don't have a solution.
I am using a node server and can connect to my database correctly with a status of 1 for connected.
However when I send requests to the mongodb database, the request pends and times out.
I have tried adding my IP to mongodb, putting my connection in an async function. and also removing mongoose and re installing it.
My structure is like this
app
client
node_modules > mongoose 5.13.14
server
node_modules > mongoose 5.13.14
My connection to mongodb is like this.
mongoose.connect(process.env.MONGOOSE_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then(res =>{
console.log("Connected to Database")
}).catch(function (reason) {
console.log('Unable to connect to the mongodb instance. Error: ', reason);
});
An example of an endpoint that fails is here.
router.get('/therapists', (req, res) => {
signUpTemplate.find({}, (err, result) => {
if (err) {
console.log(err)
} else {
res.status(200).send({
results: result
})
}
})
})
which results in error
MongooseError: Operation therapists.find() buffering timed out after 10000ms
Can someone help me please as I am really not sure what the solution is.
Thank you!
Related
I am developing an express application which connects to a MongoDB database. It is possible that my express server looses the connection to database, but how should my express server react to this scenario? I prepared the following code where i check for a lost connection and then I kill the app.
const registerCustomer = async (req, res) => {
let validRegistrationCode;
try {
validRegistrationCode = await CustomerRegistrationCode.findOne({ code: req.body.code });
} catch (error) {
if (error instanceof MongoNetworkError || error instanceof MongooseServerSelectionError) {
console.error('Mongo | Mongoose Network Error occurred');
}
process.exit(1);
}
return res.json({ obj: validRegistrationCode });
}
For every access to the DB, I have to check for a connection error and I think this makes the code ugly. How can this be improved?
I think the failure of connection to mongoDB usually doesn't happen or it can also happen in case of network is loss, or your path, syntax is not correct and what you should do is check only once when setup mongoose to connect to your database, every time you save code nodemon will help you check if you have successfully connected
// connect model with database
const mongoose = require('mongoose');
async function connect() {
try {
await mongoose.connect('mongodb://localhost:27017/collections_clothes', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// useCreateIndex: true,
});
console.log("Access Database Success!");
} catch (error) {
console.log("Access FAIL!");
}
}
module.exports = { connect };
MongoClient.connect(this._config.connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
}, (err, db) => {
if (err) {
console.log(`error on connect : ${err}`);
return console.dir(err);
}
console.log('We are connected');
this._client = db;
});
This piece helps me connect to mongodb running locally, and works fine when DBserver is up and running. But if i stop db server and then try to execute this...it doesnt call the call back. Is there a way i can get call back in case of DB is down or not reachable?
below code doesnt get call back, in case of future DB errors.
this._client.on('error', args => this.onError(args));
Because of this issue of not getting call backs, in case of any severe errors...my server goes down without showing any error.
I have a mongoose connection to a mongodb server. When the server is running and it tries to connect it works fine and only prints out the single statement to the console. But when I haven't turned the mongo server on yet it prints both statements in the order they are in the code. I know this is not a huge error but would like to not have the health check show up as 'up' when the server is actually down.
Mongoose connection code:
mongoose.connect(config.db, {autoReconnect: true}, () => console.log('MongoDB has connected successfully.'));
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
The connect callback receives an error parameter you can check:
mongoose.connect(config.db, {autoReconnect: true}, (err) => {
if (!err) console.log('MongoDB has connected successfully.');
});
You can also separately handle the 'connect' event in the same way you're handling the 'error' event:
mongoose.connection.on('connect', function() {
console.error('MongoDB has connected successfully');
});
Below code check coming connection authenticated or not
..............
..............
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
....................
.....................
above connection process only display the "error" in command prompt not response the user. How to response the client(connection error) ?
Not sure what is most popular or to best to learn, the expressjs website hello world example is about responding to a "/" path 'get' http request.
In your web app example code and using express.js, you might be checking sequelize for a database connection on each request, in which case you would do something like:
app.get('/', function(res, req) {
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
//and do something like
//send data to the client
})
.catch(err => {
console.error('Unable to connect to the database:', err);
//
res.send('Unable to connect to the database.');
});
});
This express.js documentation about basic routing might also be useful.
I'm trying to connect to my cluster on mongoDB Atlas via Mongoose.connect(), but every time i try to connect i get an exception "MongoError: authentication fail"
I know MongoDB Atlas is new mongo as a service could it be not supported by mongoose yet?.
The answer in this related post is correct. You should:
not mix options with connection string (if done so)
make sure your IP you are running on is whitelisted and your network allows connections to Atlas
make sure the user has sufficient permissions
use the connection string as is provided by atlas and just provide it to
mongoose.connect(uri);
MongoError: authentication fails - It means your name or password or dbname is not correct -
uri sample -
const uri =
"mongodb+srv://<username>:<password>#firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";
Suppose username is - najim & password is 1234 & dbname is pets (Note - default dbname is test but you can write whatever you want) then my uri will be with above credentails -
const mongoAtlasUri =
"mongodb+srv://najim:1234#firstcluster.4rc4s.mongodb.net/pets?retryWrites=true&w=majority";
to connect with moongoose
try {
// Connect to the MongoDB cluster
mongoose.connect(
mongoAtlasUri,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log(" Mongoose is connected")
);
} catch (e) {
console.log("could not connect");
}
const mongoAtlasUri =
"mongodb+srv://<username>:<password>#firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";
try {
// Connect to the MongoDB cluster
mongoose.connect(
mongoAtlasUri,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log(" Mongoose is connected"),
);
} catch (e) {
console.log("could not connect");
}
const dbConnection = mongoose.connection;
dbConnection.on("error", (err) => console.log(`Connection error ${err}`));
dbConnection.once("open", () => console.log("Connected to DB!"));
try {
mongoose.connect( uri, {useNewUrlParser: true, useUnifiedTopology: true}, () =>
console.log("connected"));
}catch (error) {
console.log("could not connect");
}
this works fine , try it
"mongodb+srv://:#cluster0.vvkuk.mongodb.net/"
also in the atlas, in security go to network access, there will be small buttons edit and delete click on edit, and in the edit, there will to two options the first option is ADD CURRENT IP ADRESS & the second option will be ALLOW ACCESS FROM ANYWHERE
go for the first option & then click confirm