![](/img/trans.png)
[英]How to call method defined in a mongoose schema while retriving complete list in a model?
[英]How to get Schema of mongoose database which defined in another model
這是我的文件夾結構:
+-- express_example
|---- app.js
|---- models
|-------- songs.js
|-------- albums.js
|---- and another files of expressjs
我在文件 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 中的代碼
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)
要在專輯.js 中的示例中獲取架構,您可以執行以下操作:
var SongSchema = require('mongoose').model('Song').schema
要從已注冊的 Mongoose 模型中獲取架構,您需要專門訪問架構:
var SongSchema = require('mongoose').model('Song').schema;
對於不熟悉 Mongoose 工作原理的更深層次的其他人來說,現有的答案可能會令人困惑。
這是從另一個文件中導入模式的通用實現示例,該文件可供來自更通用上下文的更廣泛受眾訪問。
const modelSchema = require('./model.js').model('Model').schema
這是問題中特定情況的修改版本(這將在albums.js 中使用)。
const SongSchema = require('./songs.js').model('Song').schema
從這里,我可以看到您首先訪問並要求文件通常如何要求模型,除非在這種情況下您現在專門訪問該模型的架構。
其他答案需要在變量聲明中使用 mongoose,這與之前通過聲明諸如const mongoose = require('mongoose');
類的變量需要 mongoose 的常見示例const mongoose = require('mongoose');
然后像那樣使用貓鼬。 對我來說,這樣的用例在知識上是無法訪問的。
您可以像往常一樣只需要模型,然后通過模型的架構屬性引用架構。
const mongoose = require('mongoose');
// bring in Song model
const Song = require('./songs.js');
const AlbumSchema = new Schema({
// access built in schema property of a model
songs: [Song.schema]
});
var SongSchema = require('mongoose').model('Song').schema;
您的albums.js
的上述代碼行肯定會起作用。
"songs" : [{type: Schema.Types.ObjectId, ref: 'Song', required: true}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.