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

时间:2023-02-06 02:33:21

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

我在文件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

我如何制作专辑。js知道SongSchema要定义AlbumSchema

3 个解决方案

#1


79  

You can get models defined elsewhere directly with Mongoose:

你可以在其他地方直接用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

#2


24  

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

要从已注册的Mongoose模型获得模式,您需要专门访问模式:

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

#3


3  

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

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

您的相册中的上面一行代码。js肯定会工作。

#1


79  

You can get models defined elsewhere directly with Mongoose:

你可以在其他地方直接用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

#2


24  

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

要从已注册的Mongoose模型获得模式,您需要专门访问模式:

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

#3


3  

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

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

您的相册中的上面一行代码。js肯定会工作。