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');
});
Related
I am trying to use use hyper terminal to connect to my mongodb database (created with mongoose) and when I use node app.js to try to connect to the database using hyper terminal, my terminal just freezes and return no response until I press ctrl c to exit and return to the previous line.
My mongoose code looks like the following:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB');
Please note. I have already connected to the mongodb server by using mongodin the terminal and I have also cd to the directory of my folder where the app.js is located on my pc before running the node app.js on the terminal
screenshort of my terminal hyerterminal code screen
Please I need your help. Thank you
I believe that your terminal is NOT frozen, it is just that there is no console output in your code. You are connecting to Mongoose and then doing nothing after that.
Here are some suggestions,
You can use a callback to check if the connection is connected,
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB').then(
() => {
console.log("Connected to DB!");
},
err => {
console.log(err);
}
);
Add a few event handlers to check if your connection is working,
mongoose.connection.on('open', function(){
console.log("Connection to Mongo DB is open!");
});
If you want to check for errors during "connect", you can chain an error handler in catch block.
mongoose.connect('mongodb://localhost:27017/test').
catch(error => console.log(error));
If you want to use Async/Await for the same error handling, then follow the below.
(async () => {
try {
await mongoose.connect('mongodb://localhost:27017/test');
console.log("Successfully connected to Mongo DB");
} catch (error) {
console.log(error);
}
})();
If you want to catch errors happening after the connection is connected to Mongo DB,
mongoose.connection.on('error', err => {
console.log(error);
});
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!
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 need emit an event when the connection was connected and disconnected. My problem is to detect when the connection was reestablished.
The mongo drive emit um event when the connection was disconnected (on error), but it doesn't emit a event when the connection is reestablished.
MongoClient.connect(mongoUrl, function (err, db) {
if (err) {
console.log('Error on connecting to mongo!');
console.error(err);
reconnect();
return;
}
console.log('Mongo connected!');
emit('connected', db); // This event is emitted only on the first connection.
db.on('error', function (err) {
console.log('Mongo connection broken!');
console.error(err);
emit('disconnected');
});
}
Analyzing the code I discovered the serverConfig object.
db.serverConfig.on('reconnect', function() {
console.log('DB reconnected');
});
Is it a good practice to use this internal object?
Thanks.
According to Mongo driver developers, it's a good practice to use db.serverConfig to subscribe to the 'reconnect' event.
More details in:
Database object emits a 'reconnect' event
My code:
db = mongoose.connect(
config[MONGO_HOST_CONF],
config[MONGO_ACCOUNTS_DB_CONF],
config[MONGO_PORT_CONF]
}
);
db.connection.on('opening', function() {
console.log("connecting");
});
db.connection.on('open', function() {
console.log("connected");
});
db.connection.on('error', function() {
console.log("disconnected");
});
db.connection.on('close', function() {
console.log("disconnected");
});
When I start my webserver which then opens a connection to mongodb, I can see "connected" in logs.
But when I do a mongodb stop, I dont see "disconnected" in logs. Neither do I see "connecting".
I am trying to detect if for some reason mongodb went down. Then reconnect before bailing out.
What is wrong above?
opening isn't an event that is sent by Mongoose, try connecting instead.
Also, close is an event that will be called when the client is closing the connection; in the situation where the server has stopped (or crashed), it isn't sent. Try using the disconnected event for that.