Am 22.01.2014 16:37, schrieb Kai-Heng Feng:
On Wed, 22 Jan 2014 13:05:40 +0100, Sönke Ludwig wrote:
Am 22.01.2014 04:51, schrieb Kai-Heng Feng:
I want to organize my REST APIs in different modules,
I am wondering if I useconnectMongoDB
in these classes (or even in functions)
are some kind of bad practice?Or should I use
connectMongoDB
once,
then pass theMongoClient
through class constructor?Thanks!
Passing a single
MongoClient
instance - or, maybe even better, the
derivedMongoDatabase
orMongoCollection
instances - to each class
is the best approach. EachMongoClient
contains its own connection
pool to the DB server, so creating multiple clients will also result in
multiple connections to the DB (even though this will usually not be a
severe issue).Now I passes
MongoClient
through different class's constructor, and
it works pretty well.Since
MongoClient
is a class, I should simply pass it withoutref
qualifier because it's already ref-counted, right?
Exactly, same for MongoDatabase
and MongoCollection
. Even if those
are struct
s, they basically only contain a reference to the MongoClient
, so copying them is a cheap operation.
BTW, strictly speaking, MogoClient
is not reference counted, but
managed by the garbage collector, which makes it even cheaper to
copy/pass around.
Thanks for your help again.