Defining Mongoose Models in Separate Module

后端 未结 2 417
情歌与酒
情歌与酒 2020-12-12 12:35

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 = mongo         


        
相关标签:
2条回答
  • 2020-12-12 13:08

    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.

    0 讨论(0)
  • 2020-12-12 13:21

    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'});
    
    0 讨论(0)
提交回复
热议问题