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.
Related
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!
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 };
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');
});
I'm trying to connect to mlab using node with little success. I use this line to connect to my db
mongoose.connect(mymlabDBurl, { useMongoClient: true });
I have then tried to test that it works by hitting my API end points. I know this works because the first console.log below works. However when I try and save to my database I never hit the next two console.logs. How can I test for why this connection to the db is failing?
exports.add_name = function (req, res) {
const newName = new Name(req.body);
console.log(newName); //this prints
newName.save(function (err, name) {
console.log(name); //this doesnt print
console.log(err); //this also doesnt print
if (err)
res.send(err);
res.json(name);
});
};
How do I stop queries from buffering and instead throw error when connection doesn't exist between application and database?
I'm using node-mongodb-native driver.
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://someremotedb:27017/test';
var db = null,
xcollection = null;
As suggested in this answer I am opening a connection and keeping it for later requests.
function connect() {
MongoClient.connect(url, function(err, _db) {
db = _db;
xcollection = db.collection('xcollection');
db.on('close', function() {
console.log("connection close mongoDB");
connection_retry();
});
db.on('error', function(err) {
console.log("connection err mongoDB ",err);
connection_retry();
db.close();
});
});
}
and I use it like this.
module.exports.xcollection_find = function (_x, _cb) {
try {
xcollection.findOne({x: _x}, { _id: 0 }, function(err, doc) {
if(err) return _cb(err, null);
if(doc===null) return _cb(null, {success: false, data: null});
return _cb(null, {success: true, data: doc});
});
}
catch(e) {
return _cb(e, null);
}
}
I call connect and then everything works fine as expected.
Except for when I interrupt the internet connection to the db. (ie- disconnect internet on my pc with app running), I don't see any errors. All requests made timeouts with this message.
[MongoError: server c99.kahana.mongohq.com:27017 received an error {"name":"MongoError","message":"read ETIMEDOUT"}]
But it takes around 5 to 10 minutes before the timeout occurs.
If the close or error event is thrown my reconnect function would fire which is.
function connection_retry () {
console.log("connection retry mongoDB");
setTimeout(function() {
connect();
}, 500);
}
But it never does.
If net connection is restored before the timeouts occurs(ie- 5 -10 mins), the queries are executed and the results are received.
How do I detect that the connection is down in the xcollection_find method?
Why are the on close or on error callbacks not executed?
update:
var options = {
db: {
bufferMaxEntries: 2
},
server: {
socketOptions: {
keepAlive: true,
connectTimeoutMS: 2000
},
auto_reconnect: true
}
}
MongoClient.connect(url, options, function(err, _db) {
setting bufferMaxEntries to 2 still doesn't solve problem and the requests are buffered and occurs on reconnect.
You open do MongoClient.connect once when your app boots up and reuse
the db object. It's not a singleton connection pool each .connect
creates a new connection pool. So open it once an reuse across all
requests.
https://groups.google.com/forum/#!msg/node-mongodb-native/mSGnnuG8C1o/Hiaqvdu1bWoJ
Node.js is single threaded you should not open as well as close the connection on same request.