【问题标题】:Reference array elements in same document of mongodbmongodb同一文档中的引用数组元素
【发布时间】:2020-12-10 08:13:26
【问题描述】:

这是 mongo 架构-

    {
        name: String
        description: String,
        array1: [{prop1: Number, prop2: String}],
        referencingArray: {prop1: String, prop2_array1ref: <array1 element ref>},
    }

对象类型的数组元素。 referencingArray 对象中的属性之一需要引用来自 array1 的元素。 UI 稍后将使用引用的数组元素来注释referencingArray 信息。 UI 还需要根据对array1 的更改来更新referencingArray。目前array1 对象没有任何唯一标识属性。

我的一个想法是向array1 对象添加一个guid 属性以唯一标识它们并使referencingArray 对象的prop2_array1ref 使用此guid。但这会在 array1 对象上添加一个额外的属性。

通过索引引用array1 对象需要处理从array1 中删除。如果prop2_array1ref 引用array1 的索引0 元素,则删除索引0 处的元素应该使referencingArray 处于错误状态,而不是默默地引用索引0 处的新对象。

Mongo 将 _id 属性分配给数组对象。我想过在prop2_array1ref 中使用数组对象的_id 属性,但是当数组对象还没有id 时,我不确定如何处理新条目。

问题:

referencingArray 引用array1 元素的最佳方式是什么?

编辑以添加示例:

    {
        name: 'John',
        description: 'Best guy',
        array1: [
          {prop1: 12, prop2: 'lorem'}, 
          {prop1: 55, prop2: 'ipsum'}
        ],
        referencingArray: {prop1: 'domur', prop2_array1ref: <array1 element 1 ref>},
        // User can change prop2_array1ref to point to different element of array1 in UI.
        // Question is what's a good value for prop2_array1ref?
        // Options are-
        //   1. Add guid to array1 elements and use that as value of prop2_array1ref. (e.g. 'fl3-42mnj-348hn-83ngns')
        //   2. index of array1 elements. (e.g. 1)
        //   3. mongo assigned _id of array1 elements. (e.g. 98702398420398)
    }

【问题讨论】:

  • 一个小样本数据集(只有 2 个文档)将有助于澄清问题。
  • @raga 添加了一个示例。

标签: mongodb express


【解决方案1】:

一个简单的标准化就可以完成这项工作:

你的主要模特

{
    name: String
    description: String,
    array1: [{type: Schema.Types.ObjectId, ref: 'Array1Model'}],
    referencingArray: {prop1: String, prop2_array1ref: {type: Schema.Types.ObjectId, ref: 'Array1Model'}},
}

Array1Model

{
    prop1: Number
    prop2: String
}

正如你自己所说,mongo 会隐式添加主键。稍后,如果您想在前端很好地呈现它们,您可以使用$lookup 进行简单的类似“加入”的操作。这是example

【讨论】:

  • 这是使用 mongo 提供的 id 的选项 3 的更好变体。我仍然需要处理添加新数据。
  • 更新:现在我知道了 Enter 键在 cmets 框中的作用以及评论更新的时间限制。使用 array1 中的新元素更新主文档中的对象或更新到元素也将很有趣。到目前为止,我一直在做简单的验证和更新。猜猜我需要在更新期间添加逻辑。
  • 至于更新并向 array1 添加新元素 - 是的,我相信它会是相同的形式,但您的 API 端点会期望负载 JSON 中有多个对象。然后在服务器端,您只需将相应的记录添加到 Array1Model,存储它们生成的 ID 并更新主对象的记录。至于从 Array1Model 中删除和使主对象中的引用无效 - 我相信您可以添加自己的中间件来处理这个问题,如本例所示:stackoverflow.com/questions/11904159/…
猜你喜欢
  • 1970-01-01
  • 2012-09-28
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2017-07-02
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多