代码之家  ›  专栏  ›  技术社区  ›  Simeon Nakov

Mongo在每次刷新页面时都建立新连接

  •  0
  • Simeon Nakov  · 技术社区  · 8 年前

    当我加载页面时,我希望显示一些产品,所以我发出一个get请求,它从数据库中检索它们。但是,当我刷新页面时,我注意到旧的连接仍然存在。如何确保旧的联系紧密?

    这是我的代码:

    const MongoClient = require('mongodb').MongoClient;
    
    const connection = (closure) => {
        return MongoClient.connect(config.connectionString, (err, client) => {
            if (err) {
                return winston.log('error', now() + err);
            }
            closure(client);
        });
    };
    ...
    router.get('/products', (req, res) => {
        connection((client) => {
            client.db('dbname').collection('collectionname')
                .find({})
                .toArray()
                .then((products) => {
                    response.data = products;
                    response.message = "Products retrieved successfully!"
                    res.json(response);
                })
                .catch((err) => {
                  winston.log('error', now() + err);
                  sendError(err, res);
                });
        });
    });
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Alexis Facques    8 年前

    嗯,每次你 /products 路由被调用时,您将创建一个新的mongoclient实例。在这种情况下,为了限制到数据库的连接数量,您可以连接一次,然后保存mongoclient实例:

    let client = undefined;
    const connection = (closure) => {
        // Return the client if any...
        if(client) return closure(client);
        return MongoClient.connect(config.connectionString, (err, c) => {
            if (err) {
                return winston.log('error', now() + err);
            }
            // Save the client.
            client = c;
            closure(client);
        });
    };
    

    ……或者干脆 close 完成后实例化的mongoclient连接:

    router.get('/products', (req, res) => {
        connection((client) => {
            client.db('dbname').collection('collectionname')
                .find({})
                .toArray()
                .then((products) => {
                    response.data = products;
                    response.message = "Products retrieved successfully!"
                    // Close the MongoClient...
                    client.close();
                    res.json(response);
                })
                .catch((err) => {
                  winston.log('error', now() + err);
                  sendError(err, res);
                  // Close the MongoClient...
                  client.close();
                });
        });
    });
    

    我建议您采用第一种解决方案:mongoclient维护一个连接池,因此拥有多个客户端没有任何优势。此外,它还允许您在执行任何其他操作之前检查数据库是否远程可用(只需连接到app in it()上的数据库,然后保存客户端实例,就可以了)。

    推荐文章