Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Connection Pool

I noticed in the Mongoose docs that there is support for a connection pool.

http://mongoosejs.com/docs/connections.html

Considering that node is single threaded why is there a connection pool? What's the lifecycle of connections in the pool?

like image 390
Douglas Ferguson Avatar asked Jan 18 '15 17:01

Douglas Ferguson


People also ask

What does Mongoose connection do?

Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. mongoose. connect('mongodb://localhost:27017/myapp'); const MyModel = mongoose. model('Test', new Schema({ name: String })); // Works MyModel.

What is connection pooling in MongoDB?

Definition. A connection pool is a cache of open, ready-to-use database connections maintained by the driver. Your application can seamlessly get connections from the pool, perform operations, and return connections back to the pool. Connection pools are thread-safe.

What is the difference between Mongoose connect and Mongoose createConnection?

connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used. Hope someone can clarify more about this.

Do I need to close Mongoose connection?

However, there are times when you will want to close the connection. For example, if your application is shutting down, or restarting, the database connection needs to be manually closed, or if you are running a single-hit script rather than a persistent application.


2 Answers

Connection pools don't have anything to do with async vs sync -- it just works like so:

  • You can specify an amount of open connections to maintain to your database (let's say 10).
  • Each time your Node JS code makes a query, if possible, it'll use one of the already-open 10 connections to make this request -- this way you can avoid the overhead of opening a new database connection for each query.

Maintaining a connection pool is essentially maintaining an array of db connection objects, and picking unused ones for every query. It's not actually effecting threads or processes at all =)

like image 161
rdegges Avatar answered Sep 18 '22 08:09

rdegges


apparently node is a single threaded but internally when node makes a call to IO operation under the hood it has some threading mechanism through which it performs IO. Main thread doesn't perform this IO operation itself, if it was performing IO, system would be dead already.

https://codeburst.io/how-node-js-single-thread-mechanism-work-understanding-event-loop-in-nodejs-230f7440b0ea

like image 38
Asad Mehmood Avatar answered Sep 18 '22 08:09

Asad Mehmood