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;
}
}
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([...]);
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);
});
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:
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.
But I can not understand how should I use it (for example with my cat class)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…