Pass mongoose connection to module Pass mongoose connection to module mongodb mongodb

Pass mongoose connection to module


Generally speaking you don't do this. The mindset is a little different with mongoose than working with the native driver in it's raw form, and there are plenty of things helping under the hood to make things work a bit more seamlessly without diving into the gory details.

So the basic approach is when you define your "schema" and "models", these are bound to the default connection instance. Unless you have a specific reason for binding to another connection, this is what you should follow:

So you would have a Schema and model definition:

var mySchema = new Schema({    "name": String});module.exports = mongoose.model( "Model", mySchema, "collection" )

Where the "collection" part is optional otherwise the "model" name in the first argument is put to standard rules, usually lowercase and pluralized.

Then in your other code listing, you pull this in with require:

var Model = require('./models/mymodel.js');

And use your model objects as mongoose permits:

Model.find({ "field": "name"}, function(err,models) {});

So it allows a bit more abstract handling than is done with the basic driver as the "models" themselves know how to bind to connections, or are otherwise explicitly bound to the connection you want as an optional parameter.


You can create a default Mongoose connection:

var mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/test');var db = mongoose.connection;

If you want to open multiple connections you can use createConnection:

var dbconnection = mongoose.createConnection ('uri,uri');

This connection object can then be used for creating/retrieving models that are scoped only to this connection.

The Mongoose connection object has multiple events on which you attach handlers. You should check out the documentation for the full list of handlers you can use.

To get you started, a basic approach would be:

// log connection errorsdb.on('error', console.error.bind(console, 'connection error:'));// wait for opening the connectiondb.once('open', function () {   // do something once connection to the MongoDB is open});

If you open your connection using createConnection, you need to use it when creating models:

// dbconnection is created using createConnectionvar MyModel = dbconnection.model('MyModel', MyModelSchema);