簡體   English   中英

什么是Mongoose模型屬性,包含“ ref”但未指定類型?

[英]What is a Mongoose model property that contains 'ref' but does not specify type?

Mongoose的新手-我正在做一個現有的項目,並且被賦予了更改某些模型屬性的任務。 我了解,如果模型包含此類型的屬性

postedBy: {
  type: mongoose.Schema.Types.ObjectId,
  ref: 'User'
}

此屬性引用了另一個模型/模式,要訪問該鏈接的模型/模式,需要populate它以獲得對該屬性的訪問。

但是在我正在審查的代碼(我沒有寫過)中,有很多這種類型的屬性

contentTypes: [{ ref: 'ContentType' }],
source: { ref: 'Source',required: true },

在其中引用了另一個架構,但是沒有類型。 這是同一種關系,並且暗含id嗎? 這是子文檔嗎?

另一個問題是:如果在模型中我想引用鏈接模型(或模式)的屬性,是否需要先populate 也就是說,如果它是子文檔,則只能使用點表示法,但是如果它是“鏈接”文檔,則不確定。

答案是,模型模式不是獨立存在的,而是傳遞給模型“工廠”的,這為它們提供了所需的屬性類型。

因此,來自該工廠的以下代碼段(如下)。 我查看了有關mongoose-autopopulate的文檔,但看不到autopopulate=true含義。

new: function(name, properties, statics, methods, schemaMods) {
// Add default definition to properties with references and load reference schemas
Object.keys(properties).forEach(function(key) {
  var modifiedProperty = (property) => {
    if (property.ref) {
      property.autopopulate = true;
      property.type = mongoose.Schema.Types.ObjectId;
    }

    return property;
  };

  if (Array.isArray(properties[key]) && properties[key].length === 1) {
    properties[key][0] = modifiedProperty(properties[key][0]);
  } else {
    properties[key] = modifiedProperty(properties[key]);
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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