node.js - MongoClient抛出MongoError : server instance pool was destroyed

标签 node.js mongodb

我在 SO 上看到这些帖子描述了这个错误。其中大多数是因为 JavaScript 是异步的并且 mongoClient.close() 在回调之外调用。这不是我的情况,但我不知道还有什么原因。

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url, {
    useNewUrlParser: true
});

module.exports = class Mongo {
    insertOne(article) {
        mongoClient.connect((err, client) => {
            const db = client.db('grabber');
            db.collection("zr").insertOne(article, (err, res) => {
                if (err) throw err;
                mongoClient.close();
            });
        });
    };
}

最佳答案

我观察到您在 insertOne() 方法中打开 mongoClient.connect(),并且还在其中调用 mongoClient.close()该方法,使用 mongoClient 作为全局变量。

我的预感是:

  • 还有另一个方法调用由此方法关闭的 mongoClient,或者
  • 您调用了 insertOne(article) 两次

我可以确认第二个原因是最有可能的。这是我尝试过的代码:

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url, {
    useNewUrlParser: true
});

class Mongo {
    insertOne(article) {
        mongoClient.connect((err, client) => {
            const db = client.db('grabber');
            db.collection("zr").insertOne(article, (err, res) => {
                if (err) throw err;
                mongoClient.close();
            });
        });
    };
};

x = new Mongo()
setTimeout(function() { x.insertOne({'a': 1}); }, 1000);
setTimeout(function() { x.insertOne({'a': 2}); }, 2000);

两个setTimeout是为了确保两个insertOne()被依次调用。结果:

MongoError: server instance pool was destroyed

按照当前代码的结构方式,每次调用 insertOne() 时, Node 驱动程序都会创建一个新的连接池。这不是最佳的,并且会阻止 Node 驱动程序利用连接池。

不要在 insertOne() 内调用 mongoClient.connect(),而是在 Mongo 类 外部全局调用它。将全局连接对象(从 mongoClient.connect() 返回的对象)而不是 mongoClient 对象本身传递给 insertOne() 方法。

关于node.js - MongoClient抛出MongoError : server instance pool was destroyed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54521675/

相关文章:

node.js - MongoDB 查询查找具有变体的文档

MongoDB Aggregation,有没有办法从聚合游标中获取 executionStats?

node.js - nodejs 中的数据库连接安全

javascript - 使用回调链接类方法?

mongodb - mongos 实例如何在集群中协同工作?

mongodb - 单个字段可以在 MongoDB 中设置为过期吗?

mongodb - Meteor 将自定义字段添加到 Meteor.users : should I do it?

node.js - 带有异步库的循环内的 Mongoose 异步调用

node.js - npm audit 在我升级包后提示漏洞

node.js - 奇怪的node.js + http + gm + s3 行为