我有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"
}
评论:
{
_id: ObjectId(54fd786c549e96f70f9c027e),
content: "This is a comment on a post"
}
创建帖子或评论时,还会在集合“events”中创建一个文档,其中包含名为“_reference”的属性。这个“_reference”将保留评论或帖子的ObjectId。
然后我需要恢复集合“事件”中每个文档中引用的所有文档(保存在其他集合中,即帖子和注释)。
我使用了populate方法,但只允许我在需要检查所有现有集合时签入一个集合。
Bellow是我如何在mongoose模型中定义引用属性的示例:
_reference: {type: Schema.Types.ObjectId, ref: 'posts'}
提前致谢!
答案 0 :(得分:1)
您无法定义事件的架构,如:
_reference: {type: Schema.Types.ObjectId, ref: 'posts'}
并期望它也引用评论。因为您明确告知该引用是针对帖子的。
更好的方法是在ObjectID
中为要保存的对象保存events
,添加一个名为type
的字段,您可以在其中说明是评论还是帖子,并据此,查找ObjectId
的指定集合。