Reputation: 3
I have 3 collections :
events :
{
_id: ObjectId(54ca0f2506d0c6b673b2fde8),
_reference: ObjectId("54fd786c549e96f70f9c027d")
},
{
_id: ObjectId(54acd81941a646d768922cfa),
_reference: ObjectId("54fd786c549e96f70f9c027d")
}
posts :
{
_id: ObjectId(54fd786c549e96f70f9c027d),
title: "This is a post",
content: "This is the content of the post"
}
comments :
{
_id: ObjectId(54fd786c549e96f70f9c027e),
content: "This is a comment on a post"
}
When a post or a comment is created, a document is also created in the collection "events" with a property called "_reference". This "_reference" will hold the ObjectId of the comment or post.
Then i need to recover all the documents (saved in the other collections ; i.e posts and comments) thats referenced in each document in the collection "events".
i used the populate method but that only allows me to check in ONE collection when I need to check in ALL the existing collections.
Bellow is an example of how I defined the reference property in the mongoose model :
_reference: {type: Schema.Types.ObjectId, ref: 'posts'}
Thanks in advance !
Upvotes: 0
Views: 63
Reputation: 2522
You cannot define the schema of events like:
_reference: {type: Schema.Types.ObjectId, ref: 'posts'}
and expect it to refer to comments as well. Because you're telling explicitly that the reference is for posts.
A better approach would be to save an ObjectID
in events
for the object you want to save, add a field called type
where you would say if it's a comment or a post, and according to that, look up the designated collection for the ObjectId
.
Upvotes: 1