Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using db.open with MongoDB and Nodejs

I have two questions.

First, the MongoDB documentation constantly refers to using db.open() and then db.collection(), but i have noticed that i'm still able to work with the api even without first calling db.open(). Is it safe to do so? Is the api internally calling db.open()?

http://mongodb.github.com/node-mongodb-native/api-generated/db.html#collection

Second, is there a param in the db object that specifies if db.open() was called? If not, how else could i find out if db.open() was called?

The reasoning is because i have built several functions that communicate with mongo, but when some of the functions interact with each other, i get errors that the database cant be 'opened' multiple times.

EDIT

I found this param in the db object. It appears this is a bool determining the use of the db.open() but im not 100% sure, does anyone know? db.serverConfig.internalMaster

like image 833
cnotethegr8 Avatar asked May 26 '26 15:05

cnotethegr8


2 Answers

if you need to know if a db object is connected you can check db._state == 'connected' or db.serverConfig.isConnected().

You are probably better of actually passing in a known connected object to your mvc, ensuring the db is opened before you boot up the application.

like image 117
christkv Avatar answered May 30 '26 03:05

christkv


The reasoning is because i have built several functions that communicate with mongo, but when some of the functions interact with each other, i get errors that the database cant be 'opened' multiple times.

You should reuse the db object instead of opening it multiple times - the same should be done with collection objects as there is a cost associated with creating them.

like image 27
Martin Avatar answered May 30 '26 04:05

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!