Justin Morgan
Justin Morgan

Reputation: 30715

What is the recommended lifespan for a connection in MongoDB/Mongoose?

I'm taking my first dip into the MEAN stack, and I'm working with the database through Mongoose. I'm not very familiar with Mongoose or MongoDB, so I don't know how they like to be configured. I also don't really know whether Mongoose matters or this is purely a MongoDB question.

The last time I wrote data access logic directly (without an ORM or injected repositories to handle connection management for me), it was in .NET with System.Data.SqlClient. I remember having to always make sure a SqlConnection was open no longer than necessary, and to always close it explicitly when I was done.

I've read lots of how-tos about writing MEAN apps, and nobody mentions this. From the code I've seen, I get the impression that MongoDB/Mongoose connections like to live at the application level, and that I should only be calling mongoose.connect once for the whole application.

Here's my connection code, which is called once on application startup:

mongoose = require "mongoose" 
connection = mongoose.connection 
mongoose.connect process.env.MONGO_URI

connection.on 'error', (err) ->
    console.error 'DB connection error', err
.once 'open', ->
    console.log 'DB open'

gracefulExit = -> 
    connection.close ->
        console.log 'Mongoose default connection disconnected through app termination'
        process.exit 0

process.on('SIGINT', gracefulExit)
       .on('SIGTERM', gracefulExit)

module.exports = (name, dataStructure) ->
    schema = new Schema dataStructure
    return mongoose.model(name, schema)

JavaScript translation if you need it

This is the only place mongoose.connect is called, and the resulting connection object is reused throughout the application. Am I right to do it this way, or should I be creating, opening, closing, and destroying it on each request? What other scalability issues do I need to be aware of?

I realize this sounds a little open-ended, but I'm hoping for objective information about MongoDB and Mongoose internals and configuration. Are there going to be problems when I do this in a production environment with lots of concurrent requests?

Upvotes: 0

Views: 1164

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311855

What you're creating when calling mongoose.connect is not a single connection, but a connection pool that is intended to exist for the life of your application and be shared by all code via your registered Mongoose models.

So you're already doing things correctly, and if you want to alter the default size (5) of the connection pool, you can do that via the options parameter of mongoose.connect:

// Use a pool of 3 connections.
mongoose.connect(process.env.MONGO_URI, { server: { poolSize: 3 }});

Upvotes: 1

Related Questions