嗯,每次你
/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()上的数据库,然后保存客户端实例,就可以了)。