Export and reuse my mongoose connection on multiple models

I have a directory structure

./lib ./lib/model1.js ./lib/model2.js 

Both models connect to the same MongoDB instance using mongoose, but define different models:

 // model1.js var mongoose = require ('mongoose'); mongoose.connect ('bla') var db = mongoose.connection; var schema1, model1; db.on('error', console.error.bind(console, 'database, why you no connect?')); db.once('open', function callback () { schema1 = mongoose.Schema({ // some properties }); model1 = mongoose.model1 ('model1', schema1); }); 

What is the best way to create a database connection once and reuse it for each of the models? What is the best directory structure? Maybe ./lib/middleware/db.js ?

This question seems relevant, but it uses the mpmodm npm module instead of mongoose, the question is unclear, and all of the author’s comments have been deleted.

+6
source share
2 answers

You should only call mongoose.connect once, in the application launch code. This will create a default connection pool for your application.

Your model1.js and model2.js create their models through calls to mongoose.model , which bind them to the default connection.

Thus, it is really processed for you by Mongoose.

+10
source

B. / app.js:

 var mongoose = require('mongoose'); mongoose.connect('connStr'); //connect once 

B. / lib / model1.js:

 var mongoose = require('mongoose'); var model1 = mongoose.model('model1', { foo1: { type: String, required: false}, bar1: { type: String, required: false} }); module.exports = model1; 

B. / lib / model2.js:

 var mongoose = require('mongoose'); var model2 = mongoose.model('model2', { foo2: { type: String, required: false}, bar2: { type: String, required: false} }); module.exports = model2; 

Then use this model as follows (e.g. In./routes.js):

 var model1 = require('./lib/model1.js'); var m1 = new model1({ foo: 'value_for_foo', bar: 'value_for_bar' }); m1.save(function (err) { if (err) {console.log(err.stack);} console.log('saving done...'); }); 
+8
source

All Articles