samedi 4 avril 2015

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 (CoffeeScript) 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)


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?


Aucun commentaire:

Enregistrer un commentaire