节点中的单例 MongoDB 连接
Singleton MongoDB connection in Node
在 Node 中为 Mongodb 设置单例的最佳方法是什么?我尝试了以下代码,但在快速进行大量调用时它不起作用。
单例在后续调用之前没有设置,因此它尝试打开太多连接并最终失败。下面的调用适用于进行不频繁的调用。
有人对这里的最佳做法有什么建议吗?
var db_singleon;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
var connURL = mongoURI; //set in env variables
mongodb.connect(connURL,function(err,db){
if(err)
console.error("Error creating new connection "+err);
else
{
db_singleton=db;
console.error("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
节点模块本身就是单例,只需在某处制作db
模块:
var mongo = require('mongojs');
var config = require('path/to/config');
var connection = mongo.connect(config.connection, config.collections);
module.exports = connection;
然后 require('path/to/db')
它在你的模型中,等等
在 Node 中为 Mongodb 设置单例的最佳方法是什么?我尝试了以下代码,但在快速进行大量调用时它不起作用。
单例在后续调用之前没有设置,因此它尝试打开太多连接并最终失败。下面的调用适用于进行不频繁的调用。
有人对这里的最佳做法有什么建议吗?
var db_singleon;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
var connURL = mongoURI; //set in env variables
mongodb.connect(connURL,function(err,db){
if(err)
console.error("Error creating new connection "+err);
else
{
db_singleton=db;
console.error("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
节点模块本身就是单例,只需在某处制作db
模块:
var mongo = require('mongojs');
var config = require('path/to/config');
var connection = mongo.connect(config.connection, config.collections);
module.exports = connection;
然后 require('path/to/db')
它在你的模型中,等等