javascript - 如何获取在另一个模型中定义的 Mongoose 数据库的架构

标签 javascript node.js mongodb mongoose nosql

这是我的文件夹结构:

+-- 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/

相关文章:

javascript - 如何在 Electron 中保存大文件?

javascript - Jquery 事件仅适用于页面中的元素,不适用于来自使用 ajax 的服务器的元素

node.js - 使用 Node.js 和 Angular 6 在 mongoose 中存储 PDF 文件

javascript - 如何从 Mongo 中的数组中删除元素

mongodb - mongodb go driver中维护了bson.M数组的顺序吗?

javascript - 在两个方向上迭代一个范围

php - 数以百万计的列表映射,100GB 数据顺利显示,建议

javascript - 有人可以帮助我理解在 HackerRank 上使用 JavaScript 时 Node.js 代码的用途吗?

javascript - 如何在 Atom 或任何其他 IDE 中获取 Javascript 模块的智能感知?

node.js - 解决 Webpack + Typescript 中与 Node 依赖库的类型冲突