如何处理node-mongodb-native中的连接问题

时间:2015-04-27 12:34:41

标签: node.js mongodb node-mongodb-native

当应用程序和数据库之间不存在连接时,如何阻止查询缓冲并改为抛出错误?

我正在使用node-mongodb-native驱动程序。

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://someremotedb:27017/test';
var db = null,
    xcollection = null;

作为suggested in this answer我正在打开一个连接并保留它以供以后的请求使用。

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();
        });
    });
}

我就这样使用它。

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);
    }
}

我调用connect,然后一切正常。

除非我中断与数据库的互联网连接。 (即 - 在运行应用程序的PC上断开互联网连接),我没有看到任何错误。所有请求都会通过此消息超时。

[MongoError: server c99.kahana.mongohq.com:27017 received an error {"name":"MongoError","message":"read ETIMEDOUT"}]

但是在超时发生前大约需要5到10分钟。

如果抛出close或error事件,我的重新连接函数将会触发。

function connection_retry () {
    console.log("connection retry mongoDB");
    setTimeout(function() {
        connect();
    }, 500);
}

但它永远不会 如果在超时发生之前恢复网络连接(即-5-10分钟),则执行查询并接收结果。

如何在xcollection_find方法中检测到连接已关闭?

为什么没有执行关闭或错误回调?

更新

var options = {
    db: {
        bufferMaxEntries: 2
    },
    server: {
        socketOptions: {
            keepAlive: true,
            connectTimeoutMS: 2000
        },
        auto_reconnect: true
    }
}

MongoClient.connect(url, options, function(err, _db) {

将bufferMaxEntries设置为2仍然无法解决问题,请求将被缓冲并在重新连接时发生。

1 个答案:

答案 0 :(得分:2)

  

当您的应用启动并重复使用时,您可以打开一次MongoClient.connect   db对象。它不是每个单独的连接池.connect   创建一个新的连接池。所以,一旦重用,就打开它   请求。

https://groups.google.com/forum/#!msg/node-mongodb-native/mSGnnuG8C1o/Hiaqvdu1bWoJ

Node.js是单线程的,您不应该打开以及关闭同一请求的连接。