Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Defining Mongoose Models in Separate Module

Defining Mongoose Models in Separate Module


I would like to separate my Mongoose models in a separate file. I have attempted to do so like this:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var Material = new Schema({
    name                :    {type: String, index: true},
    id                  :    ObjectId,
    materialId          :    String,
    surcharge           :    String,
    colors              :    {
        colorName       :    String,
        colorId         :    String,
        surcharge       :    Number

var SeatCover = new Schema({
    ItemName            :    {type: String, index: true},
    ItemId              :    ObjectId,
    Pattern             :    String,
    Categories          :    {
        year            :    {type: Number, index: true},
        make            :    {type: String, index: true},
        model           :    {type: String, index: true},
        body            :    {type: String, index: true}
    Description         :    String,
    Specifications      :    String,
    Price               :    String,
    Cost                :    String,
    Pattern             :    String,
    ImageUrl            :    String,
    Materials           :    [Materials]


var Materials = mongoose.model('Materials', Material);
var SeatCovers = mongoose.model('SeatCover', SeatCover);

exports.Materials = Materials;
exports.SeatCovers = SeatCovers;

Then, I have attempted to use the model like this:

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

exports.populateMaterials = function(req, res){
    for (var i = 0; i 

Is this a reasonable approach to referencing a model in a separate module?

Problem courtesy of: rob_hicks


The basic approach looks reasonable.

As an option you could consider a 'provider' module with model and controller functionality integrated. That way you could have the app.js instantiate the provider and then all controller functions can be executed by it. The app.js has to only specify the routes with the corresponding controller functionality to be implemented.

To tidy up a bit further you could also consider branching out the routes into a separate module with app.js as a glue between these modules.

Solution courtesy of: almypal


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Defining Mongoose Models in Separate Module


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription