0

如何使用 MongoDB 数据库在 NodeJS 中测试连接池?

4

1 回答 1

0

与其让我们的应用程序在连接到数据库之前等待请求,我们将在应用程序启动时让它连接,并且我们将为自己提供一个连接池,以便在需要时从中提取它们。

在这里,我们使用的是node-mongodb-native驱动程序,与大多数可用的MongoDB 驱动程序一样,它有一个选项,您可以使用它来设置连接池的大小。对于此驱动程序,它被称为poolSize,并且默认值为 5。我们可以poolsize通过提前创建数据库连接变量来使用该选项,并让驱动程序在新的连接请求进入时分配可用空间:

// This is a global variable we'll use for handing the MongoDB client
var mongodb;

// Connection URL
var url = '[connectionString]';

// Create the db connection
MongoClient.connect(url, function(err, db) {  
    assert.equal(null, err);
    mongodb=db;
    }
);

要更改默认连接池的大小,我们可以poolSize作为选项传入:

// Create the database connection
MongoClient.connect(url, {  
  poolSize: 10
  // other options can go here
},function(err, db) {
    assert.equal(null, err);
    mongodb=db;
    }
);

现在我们已经准备好连接并等待。要使用我们的新连接,我们只需要mongodb在发出请求时使用新的全局变量:

// Use the connect method to connect to the server when the page is requested
app.get('/', function(request, response) {  
    mongodb.listCollections({}).toArray(function(err, collections) {
        assert.equal(null, err);
        collections.forEach(function(collection) {
            console.log(collection);
        });
    })
    response.send('See console for a list of available collections');
});
于 2022-02-08T05:29:27.953 回答