MongoDB 的单个或多个连接更好?
Single or multiple connections to MongoDB is better?
我正在通过 Express 构建我的 Node.js 应用程序。我有两种选择来编写代码以连接到我的 MongoDB.
- 首先是每次执行查询时打开一个连接
- 其次是在启动应用程序时创建一个单一连接
然后
function productRepository(db) {
this.db = db;
};
productRepository.prototype.insert = function(item) {
return new Promise((resolve, reject) => {
this.db.collection('product').insertOne(item, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
module.exports = productRepository;
和
module.exports = function(app, db) {
var productRepository = require('../model/product');
var productRepoInstance = new productRepository(db);
app.get('/test', function(req, res) {
productRepoInstance.insert({ createdAt: new Date() }).then(
(result) => res.send({ result: 1 }),
(error) => {
console.log(error);
res.send({ result: 0 });
});
});
};
我想知道哪个更好,为什么?
您绝对应该使用多个连接,否则一次只能执行一个查询。最简洁的方法是在创建 Db 对象时简单地在 mongodb.Server 对象上启用连接池。例如:
var serverOptions = {
'auto_reconnect': true,
'poolSize': 5
};
var mohammadsMongoServer = new mongodb.Db('test', new mongodb.Server('127.0.0.1', 27017, serverOptions));
mohammadsMongoServer.open(function (err, mdb) {}
目前 mongodb 默认连接池大小为 5,但可以使用上面的示例代码增加。我建议您使用连接池而不是创建新的单独连接,因为它具有单独连接的所有优点,但通过重用连接显着减少了开销。
我正在通过 Express 构建我的 Node.js 应用程序。我有两种选择来编写代码以连接到我的 MongoDB.
- 首先是每次执行查询时打开一个连接
- 其次是在启动应用程序时创建一个单一连接
然后
function productRepository(db) {
this.db = db;
};
productRepository.prototype.insert = function(item) {
return new Promise((resolve, reject) => {
this.db.collection('product').insertOne(item, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
module.exports = productRepository;
和
module.exports = function(app, db) {
var productRepository = require('../model/product');
var productRepoInstance = new productRepository(db);
app.get('/test', function(req, res) {
productRepoInstance.insert({ createdAt: new Date() }).then(
(result) => res.send({ result: 1 }),
(error) => {
console.log(error);
res.send({ result: 0 });
});
});
};
我想知道哪个更好,为什么?
您绝对应该使用多个连接,否则一次只能执行一个查询。最简洁的方法是在创建 Db 对象时简单地在 mongodb.Server 对象上启用连接池。例如:
var serverOptions = {
'auto_reconnect': true,
'poolSize': 5
};
var mohammadsMongoServer = new mongodb.Db('test', new mongodb.Server('127.0.0.1', 27017, serverOptions));
mohammadsMongoServer.open(function (err, mdb) {}
目前 mongodb 默认连接池大小为 5,但可以使用上面的示例代码增加。我建议您使用连接池而不是创建新的单独连接,因为它具有单独连接的所有优点,但通过重用连接显着减少了开销。