3

考虑这是我的文件夹结构

express_example
|---- app.js    
|---- models    
|-------- songs.js    
|-------- albums.js    
|-------- other.js    
|---- and another files of expressjs

我在文件song.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);

在文件 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);

我可以通过以下方式获得任何模型:

require('mongoose').model(name_of_model);

但是如何通过简单的代码而不是 name_of_model 来要求特定文件夹中的所有模型?在上面的示例中,文件夹 ./models/* 中的所有模型

4

3 回答 3

8

您已将模型导出到“模型”文件夹中的每个文件中。例如,执行以下操作,

exports.SongModel = mongoose.model('Song', SongSchema);

然后在模型文件夹中创建一个名为“index.js”的通用文件并写入以下行

exports = module.exports = function(includeFile){  
  return require('./'+includeFile);
};

现在,转到您需要“Song”模型的 js 文件并添加您的模块,如下所示,

var SongModel = require(<some_parent_directory_path>+'/model')(/*pass file name here as*/ 'songs');

例如,如果我编写代码来列出songslist.js 中的所有歌曲以及放置在父目录中的文件,如下所示,

|---- models
|-------- songs.js
|-------- albums.js
|-------- other.js
|---- and another files of expressjs
|---- songslist.js

然后你可以添加“歌曲模型”,如

var SongModel = require('./model')('songs');

注意:还有更多替代方法可以实现此目的。

于 2013-01-02T14:56:29.513 回答
8
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
  require(models_path+'/'+file)
})
于 2013-01-03T05:37:21.837 回答
2

您可以使用诸如node-require-all 之类的模块,它允许您要求来自特定文件夹的所有文件(您甚至可以使用过滤条件)。

举个例子(取自模块的自述文件):

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() {...}, ...}

我认为这应该可以满足您的需求。

于 2013-01-02T11:58:00.030 回答