4

I'm trying to get my head around how mongoose uses it's connection. At the moment I have:

// Datastore.js
var mongoose = require('mongoose'),
    conn = mongoose.createConnection();

...

conn.open(host, database, port, options, callback); // Opens connection


// Model.js
var mongoose = require('mongoose');
var Schema = new mongoose.Schema({...})
module.exports = exports = mongoose.model('MyModel', Schema);


// Controller.js
var mongoose = require('mongoose');
var MyModel = mongoose.model('MyModel'); // Retrieves the model ok

MyModel.find({}, function(err, docs){
   if(err){} //
   console.log(docs); // Does not work
});

However this doesn't work... it only works if somehow I pass the connection across like so:

// Datastore.js
var mongoose = require('mongoose'),
    conn = mongoose.createConnection();

...

conn.open(host, database, port, options, callback); //

mongoose.set('db', conn);


// Controller.js
var mongoose = require('mongoose'),
    db = mongoose.get('db');

var MyModel = db.model('MyModel'); // Retrieve the model using the connection instance

MyModel.find({}, function(err, docs){
   if(err){} //
   console.log(docs); // Works
});

I think I'm approaching this in the wrong way... should the first approach work, and I'm doing something wrong?

leepowell
  • 3,838
  • 8
  • 27
  • 35

2 Answers2

8

It's easiest to just open the default connection pool that's shared by all your mongoose calls:

// Datastore.js
var mongoose = require('mongoose'),
    db = mongoose.connect('localhost', 'dbname');

Then in all your other files access the pool using mongoose.model(...).

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Thanks - how do I go about setting up the default connection? – leepowell Aug 21 '12 at 13:59
  • That's what the `mongoose.connect` call does. I added the typical parameters. – JohnnyHK Aug 21 '12 at 14:02
  • Thank you - I'm not sure the difference between this, and the method I was using and why the two technique differ in the models accessing the connection. – leepowell Aug 21 '12 at 15:43
  • @leepowell If you use your original method, you'd need to pass around `conn` everywhere and call `conn.model` instead of `mongoose.model`. – JohnnyHK Aug 21 '12 at 15:56
  • 1
    this no longer works if you use your model in more than one place. https://github.com/LearnBoost/mongoose/issues/1249 – chovy Dec 14 '12 at 06:00
2

Looking at the docs it says:

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');

Perhaps you need to put your connection details in for the create Connection

var mongoose = require('mongoose'),
conn = mongoose.createConnection('localhost', 'test');
Bino Carlos
  • 1,357
  • 8
  • 10
  • The connection part is fine, I have it connecting successfully. Using 'open' just defers the timing of the connection taking place. – leepowell Aug 21 '12 at 11:53