Why is there separate mongo.Server and mongo.Db in mongodb-native driver? Why is there separate mongo.Server and mongo.Db in mongodb-native driver? mongodb mongodb

Why is there separate mongo.Server and mongo.Db in mongodb-native driver?


For what it's worth, you can do what you want to do by using Db#db(), which doesn't seem to appear in the official documentation but is listed in the source code of db.js as being a public API:

/*** Create a new Db instance sharing the current socket connections.** @param {String} dbName the name of the database we want to use.* @return {Db} a db instance using the new database.* @api public*/

so you could do

var serv=mongo.Server("localhost", 27017);var dbase=mongo.Db("MyDatabase", serv);var dbase2=dbase.db("MyDatabase2");


Here is a link to the solution on the mongo docs, for reference. (seems like the same solution the other poster mentioned)

http://mongodb.github.com/node-mongodb-native/markdown-docs/database.html#sharing-the-connections-over-multiple-dbs

The point of separating the connection to the mongo server, and then the DB is for cases like when you want to connect to a ReplSet server, or other custom params. This way, you have a separate process connecting to a mongodb server.

The database connection call is separate simply because of the case you have here: you dont simply want to connect to a mongo server and a single db, but multiple dbs. This separation of connecting to db and server allows this flexibility.

Another Solution: Use node-mongoskin

Mongoskin does what you want to... it allows connecting to server and db all in one command. Not a solution for mongo-native, but worth considering as an alternative library for your future projects.

var mongo = require('mongoskin');var db = mongo.db('localhost:27017/testDB');


Because these are two separate and distinct actions - you have to connect (or already have a connection) to DB server (computer) in order to query any of the databases on that particular server. You can create distinct database query connections for each of the databases that you will want to use, but at the same time you will be using the same connection to the server.
Most of the time you will NOT want to create a separate server connection for each of the databases (if there are many) because the server usually limits the number of connections.