[英]Referencing an object with an unknown model-type with Mongoose
您可以采用兩種方法。
基於“ 跨數據庫填充 ”部分。 調用populate
,可以指定要使用的模型。
Like.find().populate({
path: 'target',
model: 'Photo'
})
這要求您在填充之前知道所需的模型。
基於“ 動態參考 ”部分。
您需要首先將target
調整為類似於以下內容:
var Like = new Mongoose.Schema({
target: {
kind: String,
item: {
type: Schema.Types.ObjectId,
refPath: 'target.kind'
}
}
});
target.kind
是將用於populate
的“ ref”值,而target.item
是ObjectId。 我們使用refPath
而不是ref
進行動態引用。
然后,當您調用populate
,您將改為執行以下操作:
Like.find().populate('target.item')
注意,我們填充'target.item'
而不是'target'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.