My understanding on the official documentation is that generally when there is only one connection mongoose.connect() is use, whereas if there is multiple instance of connection mongoose.createConnection() is used.
Yes. To be exact, .connect()
creates actually a pool of sockets/connections (defined in poolSize
in the connection settings, the default is 5) it keeps open, so there is actually multiple connections, but in a single pool.
That being said, if you want multiple connections pools, with different properties, you should use createConnection
Also, if my understanding is correct, what are the disadvantages of
using mongoose.createConnection() in single connection? Why it is not
advisable that we use mongoose.createConnection() for every case to
standardize the connection?
This is a good question and there's also already an answer in the docs:
Mongoose creates a default connection when you call mongoose.connect(). You can access the default connection using mongoose.connection.
Basically .connect
is a shorthand for a set of (mostly) best practice settings for createConnection
In most simple projects, you needn't worry about specifying different read or write settings, pool sizes, separate connections to different replica servers etc., that's why .connect
exists.
However, if you have more demanding requirements (e.g. for legal or performance reasons), you will probably have to use createConnection
.
A couple of weeks ago, I ran into a situation, where one of my (in-house) statistics packages needed database access with a sporadic, yet big load. Since I didn't want to pass the db/mongoose object down to the package to keep it as modular as possible, I just created a new connection. This worked very well, because I only needed to access a certain Model I defined in the package and not the ones defined in my "parent"-package. Since the new package only needed read-access and could read from a different slave/replica db to reduce the load on the main one, I switched to createConnection on both ends to separate the connection from the main one.
For me, the big disadvantage of creating multiple connections in the same problem, is the fact that you can not directly access your models through mongoose.model
, if they were defined "in" different connections. This answer details that problem: https://stackoverflow.com/a/22838614/2856218