dulan
dulan

Reputation: 1604

nodejs mongodb connect/disconnect pattern

I'm using sails.js with mongodb for my backend. And I've heard that connecting to database for each request can be really expensive, that's why other non-single threaded programming languages hold a connection pool for database right? So I wonder

  1. Does Nodejs utilize database connection pool?(I think I already have an answer which is NO, just to make sure)
  2. Since I'm using sails-mongo as mongodb driver, does it establish a new connection to mongodb each time I do some instructions to my mongodb? Or does it simply hold one connection and reuse it everytime?
  3. Assuming sails-mongo connects to the mongodb everytime and then disconnect when I'm done with it, what if the connection cannot be established? Will that jam the node thread, thus all later on requests could not be handled? I'm worried...

Upvotes: 1

Views: 1442

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50436

You presumption falls apart at 1., as every nodejs driver I know of ( including the common driver in sails) implements the node-native-driver which does of course initialize a connection pool ( 5 connections by default ).

As for point 2, The connection is actually made on application startup and model definitions utilize the underlying "Collection" objects.

And for 3, well apart from generally being "de-bunked" then the whole concept of nodejs in general is that it runs on an event engine, so in fact all "long running IO" works on callbacks so that other code may execute while those IO calls "take their time" to respond. If anything, you get an error if the connection "goes away" for any reason.

I would generally suggest a "search" on "How does nodejs work?" to fill you in on a few concepts you don't seem to be generally grasping.

So not just the case with MongoDB, but all good database drivers just about always implement a connection pool due to the inherrent cost of creating connections, and asynchronous environments are specifically "tooled" so they do not "block" when doing things like external IO.

Upvotes: 2

Related Questions