如何获取另一个模型中定义的mongoose数据库的Schema

这是我的文件夹结构:

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

我的代码在文件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} }); module.exports = 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: '.http://img.dovov.comU1.jpg'} , date: {type: Date, default: Date.now()} , songs: [SongSchema] }); module.exports = mongoose.model('Album', AlbumSchema); 

如何让albums.js知道SongSchema被定义为AlbumSchema

您可以直接使用Mongoose获得在别处定义的模型:

 require('mongoose').model(name_of_model) 

要在albums.js中的示例中获取架构,可以这样做:

 var SongSchema = require('mongoose').model('Song').schema 

要从已注册的Mongoose模型中获取模式,您需要特别访问该模式:

 var SongSchema = require('mongoose').model('Song').schema; 
 var SongSchema = require('mongoose').model('Song').schema; 

上述的albums.js代码行肯定会起作用。