相关疑难解决方法(0)

使用Node.js和mongodb处理超时

我目前正在测试一些代码如何抵制以下场景:

  • 启动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 …
Run Code Online (Sandbox Code Playgroud)

javascript error-handling timeout mongodb node.js

18
推荐指数
1
解决办法
1万
查看次数

标签 统计

error-handling ×1

javascript ×1

mongodb ×1

node.js ×1

timeout ×1