Node.js + MongoDB + Express + Mongoose.如何通过简单的代码要求特定文件夹中的所有模型?

Amo*_*rni 3 models mongoose mongodb node.js

考虑这是我的文件夹结构

express_example
|---- app.js    
|---- models    
|-------- songs.js    
|-------- albums.js    
|-------- other.js    
|---- and another files of expressjs
Run Code Online (Sandbox Code Playgroud)

我的文件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);
Run Code Online (Sandbox Code Playgroud)

在文件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);
Run Code Online (Sandbox Code Playgroud)

我可以得到任何模型:

require('mongoose').model(name_of_model);
Run Code Online (Sandbox Code Playgroud)

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

HIL*_*EEN 8

您已在"model"文件夹中的每个文件中导出模型.例如,执行以下操作,

exports.SongModel = mongoose.model('Song', SongSchema);
Run Code Online (Sandbox Code Playgroud)

然后在模型文件夹中创建一个名为"index.js"的公共文件,并写下以下行

exports = module.exports = function(includeFile){  
  return require('./'+includeFile);
};
Run Code Online (Sandbox Code Playgroud)

现在,转到您需要"Song"模型的js文件,并按如下方式添加模块,

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

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

|---- models
|-------- songs.js
|-------- albums.js
|-------- other.js
|---- and another files of expressjs
|---- songslist.js
Run Code Online (Sandbox Code Playgroud)

然后你可以添加"歌曲模型"之类的

var SongModel = require('./model')('songs');
Run Code Online (Sandbox Code Playgroud)

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


Amo*_*rni 8

var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
  require(models_path+'/'+file)
})
Run Code Online (Sandbox Code Playgroud)