I am facing an issue with retrieving all the votes associated with a comment after performing a graphlookup.
My objective is to recursively obtain the comments and their corresponding votes in a thread.
Here are my 3 schemas:
comments
- _id
- points
- content
- userId
- parentId
- parentThreadId
threads
- _id
- upvotes
- downvotes
- title
- content
- userName
votes
- _id
- vote
- commentId
- userId
The challenge lies in the comment having two keys. 'parentId' is set only if the comment is a child of another comment, while 'parentThreadId' is set for top-level comments under a thread.
With the current code, I am only able to retrieve the votes associated with top-level comments (those with parentThreadId), rather than votes from all comments.
const threadId = req.params.id;
const ObjectId = mongoose.Types.ObjectId;
Thread.aggregate([
{
$match: {_id : ObjectId(threadId)}
},
{
$lookup:
{
from: 'comments',
as: 'comments',
pipeline: [
{
$match: {parentThreadId : ObjectId(threadId)}
},
{
$graphLookup: {
from: "comments",
startWith: "$_id",
connectFromField: "_id",
connectToField: "parentId",
as: "children",
depthField: "level",
}
},
{
$lookup :
{
from: 'votes',
localField: '_id',
foreignField: 'commentId',
as: 'votes'
}
},
]
}
}
]).
If anyone has any insights on how to resolve this issue, please share!