Consider this is my folder structure
-- express_example
|---- app.js
|---- models
|-------- songs.js
|-------- albums.js
|-------- other.js
|---- and another files of expressjs
my code in file songs.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var SongSchema = new Schema({
name: {type: String, default: 'songname'}
, link: {type: String, default: './data/train.mp3'}
, date: {type: Date, default: Date.now()}
, position: {type: Number, default: 0}
, weekOnChart: {type: Number, default: 0}
, listend: {type: Number, default: 0}
});
mongoose.model('Song', SongSchema);
in file albums.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var AlbumSchema = new Schema({
name: {type: String, default: 'songname'}
, thumbnail: {type:String, default: './images/U1.jpg'}
, date: {type: Date, default: Date.now()}
, songs: [SongSchema]
});
mongoose.model('Album', AlbumSchema);
I can get any model by:
require('mongoose').model(name_of_model);
But how to require all the models in a particular folder by a simple code not by name_of_model? In above example all models in the folder ./models/*
You have export your model in each of files in "model" folder. For example, do as follows,
exports.SongModel = mongoose.model('Song', SongSchema);
Then create a common file in model folder with name "index.js" and write following line
exports = module.exports = function(includeFile){
return require('./'+includeFile);
};
Now, Go to your js file where you need "Song" model and add your module as follows,
var SongModel = require(<some_parent_directory_path>+'/model')(/*pass file name here as*/ 'songs');
For example, If i write the code to list all songs in songslist.js and file placed in parent directory as follows,
|---- models
|-------- songs.js
|-------- albums.js
|-------- other.js
|---- and another files of expressjs
|---- songslist.js
Then you can add "songs model" like
var SongModel = require('./model')('songs');
Note: There are more alternate ways to achieve this.
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
require(models_path+'/'+file)
})
You might use a module such as node-require-all which allows you to require all files from a specific folder (you can even use filter criteria).
To give you an example (taken from the module's readme file):
var controllers = require('require-all')({
dirname : __dirname + '/controllers',
filter : /(.+Controller)\.js$/,
excludeDirs : /^\.(git|svn)$/
});
// controllers now is an object with references to all modules matching the filter
// for example:
// { HomeController: function HomeController() {...}, ...}
I think that this should fulfill your needs.