I am just learning mongodb-native driver for nodejs.
I connect like this.
var mongo=require("mongodb")
var serv=mongo.Server("localhost", 27017)
var dbase=mongo.Db("MyDatabase", serv)
And that works. But if I try to create a new database connection using the same server I get an error.
var dbase2=mongo.Db("MyDatabase2", serv)
"Error: A Server or ReplSet instance cannot be shared across multiple Db instances"
But it works if a make a new server connection first.
var serv2=mongo.Server("localhost", 27017)
var dbase2=mongo.Db("MyDatabase2", serv2)
So my question is why there are 2 connection functions, one for Server and one for Db, when it seems like they must always be used together?
Why doesn't it go like this.
var dbase=mongo.Db("localhost", 27017, "MyDatabase")
I want to make my own function that does this, but I wonder if there is some other reason they are separate.
Thanks.
Here is a link to the solution on the mongo docs, for reference. (seems like the same solution the other poster mentioned)
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');