How to get Schema of mongoose database which defin

2019-01-16 06:00发布

This is my folder structure:

+-- express_example
|---- app.js
|---- models
|-------- songs.js
|-------- albums.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}
});

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

And here is my code 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]
});

module.exports = mongoose.model('Album', AlbumSchema);


How can I make albums.js know SongSchema to be defined AlbumSchema

3条回答
可以哭但决不认输i
2楼-- · 2019-01-16 06:25
var SongSchema = require('mongoose').model('Song').schema;

The above line of code in your albums.js will surely work.

查看更多
迷人小祖宗
3楼-- · 2019-01-16 06:26

You can get models defined elsewhere directly with Mongoose:

require('mongoose').model(name_of_model)

To get the schema in your example in albums.js you can do this:

var SongSchema = require('mongoose').model('Song').schema
查看更多
女痞
4楼-- · 2019-01-16 06:38

To get the schema from a registered Mongoose model, you need to access the schema specifically:

var SongSchema = require('mongoose').model('Song').schema;
查看更多
登录 后发表回答