我目前正在测试一些代码如何对抗以下场景:
- node .js应用程序启动并成功建立到mongodb的连接
- 成功建立连接后,mongodb服务器死亡,所有后续请求失败
为了做到这一点,我得到了以下使用官方驱动程序的代码(在这里找到:https://github.com/mongodb/node-mongodb-native):
MongoClient.connect('mongodb://localhost:27017/testdb', function(err, db) {
app.get('/test', function(req, res) {
db.collection('users', function (err, collection) {
console.log(err);
if (err) {
// ## POINT 1 ##
// Handle the error
}
else {
collection.find({ 'username': username }, { timeout: true }).toArray(function(err, items) {
console.log(err);
if (err) {
// ## POINT 2 ##
// Handle the error
}
else {
if (items.length > 0) {
// Do some stuff with the document that was found
}
else {
// Handle not finding the document
}
}
});
}
});
});
});
由于mongodb服务器在处理请求时不再运行,我假设在我标记为##点1#或##点2#的点上,它将返回一个指示超时的错误;然而,事实并非如此.
我try 了许多不同的设置(包括你可以在这里看到的明确允许光标超时的设置),但是我似乎无法以任何方式启用它.在我try 过的每种配置中.js只会一直等待find()操作回调,但它永远不会这样做.
如果我启动 node .运行mongodb的js应用程序before会捕获连接回调中的错误,但如果连接在此之后终止,它似乎不会以任何方式处理它.
我是否缺少一个设置,或者在建立连接后无法检测到连接被终止?
Edit: just to be clear, the username variable used in the find method is actually declared in my full code, the code I've put in this post is a cut down version to illustrate the structure and error checking.