【问题标题】:Finding a referenced document in all the existing collection using Mongoose使用 Mongoose 在所有现有集合中查找引用文档
【发布时间】:2015-05-10 15:35:22
【问题描述】:

我有 3 个收藏:

事件:

{
   _id: ObjectId(54ca0f2506d0c6b673b2fde8),
   _reference: ObjectId("54fd786c549e96f70f9c027d")
},
{
   _id: ObjectId(54acd81941a646d768922cfa),
   _reference: ObjectId("54fd786c549e96f70f9c027d")
}

帖子:

{
   _id: ObjectId(54fd786c549e96f70f9c027d),
   title: "This is a post",
   content: "This is the content of the post"
}

cmets:

{
   _id: ObjectId(54fd786c549e96f70f9c027e),
   content: "This is a comment on a post"
}

创建帖子或评论时,还会在集合“events”中创建一个文档,该文档具有名为“_reference”的属性。此“_reference”将保存评论或帖子的 ObjectId。

然后我需要恢复集合“事件”中每个文档中引用的所有文档(保存在其他集合中;即帖子和 cmets)。

我使用了填充方法,但它只允许我在需要签入所有现有集合时签入一个集合。

下面是我如何在猫鼬模型中定义参考属性的示例:

_reference: {type: Schema.Types.ObjectId, ref: 'posts'}

提前致谢!

【问题讨论】:

    标签: javascript mongodb mongoose mongoose-populate


    【解决方案1】:

    您不能定义事件的架构,例如:

    _reference: {type: Schema.Types.ObjectId, ref: 'posts'}
    

    并期望它也引用 cmets。因为您明确指出引用是针对帖子的。

    更好的方法是在events 中为您要保存的对象保存一个ObjectID,添加一个名为type 的字段,您可以在其中说明它是评论还是帖子,然后据此,查找ObjectId 的指定集合。

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 1970-01-01
      • 2015-03-24
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2021-12-03
      相关资源
      最近更新 更多