这是我的文件夹结构:
+-- express_example
|---- app.js
|---- models
|-------- songs.js
|-------- albums.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}
});
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: './images/U1.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
关于javascript - 如何获取在另一个模型中定义的 Mongoose 数据库的架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8730255/