Exporting a mongoose database module


I need to export my mongoose database module, so I could use my defined models from every module in my program.

For example, my database.js module looks something like that:

var mongoose = require('mongoose'),
    db = mongoose.createConnection('mongodb://localhost/newdb'),
    Schema = mongoose.Schema;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
    console.log("Connected to database newdb");

    var dynamicUserItemSchema = new mongoose.Schema({
      userID: Number,
      rank:  Number,

    var staticUserItemSchema = new mongoose.Schema({
        _id: Schema.Types.Mixed,
        type: Schema.Types.Mixed,

    var DynamicUserItem = db.model('DynamicUserItem', dynamicUserItemSchema);
    var StaticUserItem = db.model('StaticUserItem', staticUserItemSchema);


I want to be able adding var db = require('../my_modules/database'); to any other module my program - so I will be able to use the models like that:

db.DynamicUserItem.find(); or item = new db.DynamicUserItem({});

Is it possible doing that using "exports" or "module exports" ? Thanks.

12/2/2012 10:47:14 AM

Accepted Answer

I usually don't use the error and open events and follow the example from mongoosejs to create a connection to my db. Using the example you could do the following.


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

var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);

module.exports = Cat; // this is what you want

and then in your app.js you can do something like

var Cat = require('db');

var peter = new Cat();

Hope that helps!

12/2/2012 11:47:14 AM

You can use exports to define a module that can be required elsewhere:


var ListSchema = new Schema({
    name                : { type: String, required: true, trim: true }
    , description   : { type: String, trim: true }

module.exports = db.model('List', ListSchema);


var list = module.exports = {};

var List = require('../models/list');

list.get = function(req, res){
        List.find({ user: user._id }).exec(function(err, lists){
            res.render('lists', {
                lists: lists,


app.get('lists', routes.lists.get);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow