Reputation: 5001
I am creating a Node.js application through Express.js foundation and my knowledge lead me to create a models
folder and a file for each model. Ok, so far, so good — but the point is: each model of mine has the following fragment of code on its top:
var mongoose = require ('mongoose')
, database = mongoose.createConnection('mongodb://localhost:27017/test');
Am I repeating myself doing this? I'm not searching for "the best approach ever", but doing this is not a bad design thing?
If this is something normal, could someone explain me why this behavior happens? Couldn't I create an organic mechanism to establish a connection and just distribute its properties for the entire application?
I already worked on Rails, C# and PHP and I've never see something like this before. Probably because database connections were for me something very abstract — I touched just a few times on the connection bridge.
DISCLAIMER: My question is really very specific. I just want to know if there's a way to announce the database connection from one file to the rest of the application.
Upvotes: 0
Views: 42
Reputation: 311925
What you're doing is not typical.
Unless you have a specific need to do something else, call mongoose.connect
once during app startup and register all models using mongoose.model
.
This lets your app share a common connection pool. You can tweak the size of the connection pool via the options provided in the mongoose.connect
call.
Upvotes: 1