Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export and reuse my mongoose connection across 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 the 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's using the mongodb npm module instead of mongoose, the question is unclear, and all of the author's comments have been deleted.

like image 519
JuJoDi Avatar asked Apr 25 '14 12:04

JuJoDi


2 Answers

You should only be calling mongoose.connect once, in your application's startup code. That will create the default connection pool for your application.

Your model1.js and model2.js files create their models via calls to mongoose.model which binds them to the default connection.

So it's actually handled for you by Mongoose.

like image 84
JohnnyHK Avatar answered Sep 23 '22 18:09

JohnnyHK


In ./app.js:

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

In ./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;

In ./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 these model like this (In ./routes.js for example):

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...');
});
like image 37
Đức Nguyễn Avatar answered Sep 21 '22 18:09

Đức Nguyễn