使用node.js和mongo设置单例连接 [英] Setting up singleton connection with node.js and mongo
问题描述
以前,我将mongodb与php一起使用,并且查询使用单例的数据库.这样,我仅实例化了一次连接,然后重用了它:
Previously I used mongodb with php and to query a database I was using a singleton. This way I instantiated connection only once and then reused it:
class MDB{
protected static $instance;
public static function use(){
if(!self::$instance) self::$instance = new MongoClient();
$db = self::$instance->selectDB('DB_name');
return $db;
}
}
比我可以创建Cats类,并使用以下方法添加addCat和showCats方法:
Than I can create class Cats and have too methods addCat and showCats with something like this:
MDB::use->{'cats'}->insert([...]);
MDB::use->{'cats'}->find([...]);
现在,我开始将mongodb与node.js一起使用. Mongodb教程给我看像这样的东西:
Right now I started to use mongodb with node.js. Mongodb tutorial shows me something like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
collection.insert(doc1);
});
这基本上告诉我,我必须将所有节点操作设置为connect内部的回调.阅读此人提供的类似的问题:
Which basically tells me that I have to set up all node operations as a callback inside of connect. Reading similar question the person offers:
您的应用程序启动并重新使用时,您只需打开一次do MongoClient.connect db对象.每个.connect都不是一个单例连接池. 创建一个新的连接池.
You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.
但是我不知道应该如何使用它(例如与cat类一起使用)?
But I can not understand how should I use it (for example with my cat class)?
推荐答案
以下是对单例使用异步等待的方法. 在我的 db.js
Here is what uses async await on singleton. In my db.js
var MongoClient = require('mongodb').MongoClient;
var DbConnection = function () {
var db = null;
var instance = 0;
async function DbConnect() {
try {
let url = 'mongodb://myurl.blablabla';
let _db = await MongoClient.connect(url);
return _db
} catch (e) {
return e;
}
}
async function Get() {
try {
instance++; // this is just to count how many times our singleton is called.
console.log(`DbConnection called ${instance} times`);
if (db != null) {
console.log(`db connection is already alive`);
return db;
} else {
console.log(`getting new db connection`);
db = await DbConnect();
return db;
}
} catch (e) {
return e;
}
}
return {
Get: Get
}
}
module.exports = DbConnection();
在所有将使用相同连接的模块中
And in all modules that will use the same connection
var DbConnection = require('./db');
async function insert(data) {
try {
let db = await DbConnection.Get();
let result = await db.collection('mycollection').insert(data);
return result;
} catch (e) {
return e;
}
}
这篇关于使用node.js和mongo设置单例连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!