如何获取在另一个模型中定义的猫鼬数据库的架构 [英] How to get Schema of mongoose database which defined in another model

查看:20
本文介绍了如何获取在另一个模型中定义的猫鼬数据库的架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文件夹结构:

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

我在文件songs.js 中的代码

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);

这是我在文件专辑.js 中的代码

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);


我怎样才能让albums.js知道SongSchema被定义AlbumSchema


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

推荐答案

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

You can get models defined elsewhere directly with Mongoose:

require('mongoose').model(name_of_model)

要在专辑.js 中的示例中获取架构,您可以执行以下操作:

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

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

这篇关于如何获取在另一个模型中定义的猫鼬数据库的架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆