簡體   English   中英

用Mongoose引用具有未知模型類型的對象

[英]Referencing an object with an unknown model-type with Mongoose

當該文檔的模型/類型未知時,是否可以使用Mongoose引用另一個對象的字段?

例如,我有以下模型:照片,評論,提交,帖子等,並且我想有一個引用它們的“贊”模型:

var Like = new Mongoose.Schema({
  // What would the value of `ref` be, should it just be left out?
  target: { type: Schema.Types.ObjectId, ref: '*' }
});

據我了解, ref必須是一個模型。 我可以將其全部排除在外,但是我還能以這種方式從貓鼬的填充方法中受益嗎?

您可以采用兩種方法。

1.在調用填充時傳遞ref的值

基於“ 跨數據庫填充 ”部分。 調用populate ,可以指定要使用的模型。

Like.find().populate({
  path: 'target',
  model: 'Photo'   
})

這要求您在填充之前知道所需的模型。

2.將ref的值與目標一起存儲

基於“ 動態參考 ”部分。

您需要首先將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM