Mongolian and model compounds

I am trying to understand how the mongoose uses this compound. 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 does not work ... it only works if somehow I pass the connection like this:

 // 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 that I am approaching this wrong ... should the first approach work and am I doing something wrong?

+4
source share
2 answers

The easiest way is to simply open the default connection pool, which will be used by all your mongoose calls:

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

Then, in all your other files, the pool is accessed using mongoose.model(...) .

+8
source

Looking at the docs , he says:

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

You may need to provide connection information to create a connection.

 var mongoose = require('mongoose'), conn = mongoose.createConnection('localhost', 'test'); 
+2
source

All Articles