Defining Mongoose Models in Separate Module

I like to define the database outside of the models file so that it can be configured using nconf. Another advantage is that you can reuse the Mongo connection outside of the models.

module.exports = function(mongoose) {
    var Material = new Schema({
        name                :    {type: String, index: true},
        id                  :    ObjectId,
        materialId          :    String,
        surcharge           :    String,
        colors              :    {
            colorName       :    String,
            colorId         :    String,
            surcharge       :    Number
        }
    });
    // declare seat covers here too
    var models = {
      Materials : mongoose.model('Materials', Material),
      SeatCovers : mongoose.model('SeatCovers', SeatCover)
    };
    return models;
}

and then you would call it like this…

var mongoose = require('mongoose');
mongoose.connect(config['database_url']);
var models = require('./models')(mongoose);
var velvet = new models.Materials({'name':'Velvet'});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)