【问题标题】:ref to filed of collection instead of collection mongodb引用集合字段而不是集合 mongodb
【发布时间】:2018-10-26 06:27:57
【问题描述】:

我有这样的架构

const Schema1 = new Schema({
  field11: String,
  field12: [
             {  _id: Schema.Types.ObjectId, 
                title: String
             }
           ]
})

和另一个模式,它有一个字段来引用第一个集合的字段,如下所示

const Schema2 = new Schema({
  field21: String,
  field22: [
             {_id: {type: Schema.Types.ObjectId}, 
             {ref: 'Schema1.filed12'}
           ]
})

我需要在 schema2 中填充 field22。我需要怎么做。

以下查询对我不起作用。

Schema2.find(field21).populate('Schema1.field12')

【问题讨论】:

  • {ref: 'Schema1.filed12'}有错别字...
  • 这不是错字。像这样的裁判不适合我。
  • 出现 MissingSchemaError 错误:尚未为模型“Schema1.field12”注册架构
  • 这不是问题兄弟。问题在于在另一个集合中提交的参考。

标签: mongodb mongoose populate


【解决方案1】:

根据documentation

ref 选项告诉 Mongoose 在填充过程中使用哪个模型,在我们的例子中是 Story 模型。我们在此处存储的所有_ids 必须是来自Story 模型的文档_ids。

您正在尝试将非 ID 字段存储为引用,该引用应指向嵌套在您的 Schema1 模型数组中的子文档。这根本行不通。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多