Unexpected behavior encountered when using MongoDB's aggregate function

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!

Answer №1

Recently, I encountered a similar issue where there was a recursive relationship between documents in a collection. The only solution was to recursively make requests for each level of comments to retrieve the entire tree.

A better approach would be to store the entire comment tree within the topmost document. By doing so, the responsibility of managing the tree is shifted to JavaScript, making it easier to navigate through and update the tree when needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery's $.ajax and $.each functions to iterate through an array

I'm currently working on integrating the NY Times article search API and I need to display the results as a new list element in HTML. However, I am facing difficulties while using the $.each() function to iterate through the JSON data. My goal is to i ...

What is the process for creating a see-through background?

I'm not sure if this question has been asked before, so please forgive me and provide a link if it has. However, I haven't come across it on here yet. My aim is to create a transparent background that displays the wallpaper of the laptop's ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

What is the best way to safely distribute the same npm package with multiple contributors?

Imagine a collaborative open source project with multiple contributors working on it. As the project progresses, these contributors need to publish their work to the NPM registry. But how can this be done securely when multiple people are involved? The ow ...

Troubleshooting Nested jQuery Plugin Selector Problems

I'm looking to have the ability to nest one plugin inside another. However, my selectors seem too broad and are capturing elements within the nested plugin as well. For instance, consider the following HTML structure: <div class="my-plugin"> ...

When velocity exceeds a certain threshold, collision detection may become unreliable

As I delve into detecting collisions between high-velocity balls, an obstacle arises. This issue seems to be quite common due to the nature of fast-moving objects colliding. I suspect that the solution lies within derivatives, and while I've drafted s ...

The "Auto Load More" feature is only loading the first two pages when scrolling down

I have set up an auto load more feature that triggers on page scroll down. Although my jQuery/ajax code is functioning properly, it only loads the first 2 pages automatically as I scroll down. There are more pages/records available but the loading process ...

I am experiencing difficulties with my jQuery animation function as it does not seem to be functioning properly despite successful

Can someone knowledgeable in jQuery and JavaScript please help me understand why this code isn't functioning as expected? The goal is for the image with the id "previmage" to expand and then shrink when the changeclass function is triggered. However ...

Organizing Data with Mongodb Aggregation and Array Sorting

Since the $ positional operator does not work for nested arrays that are 2 levels deep, I have implemented an alternative schema to allow for updating nested arrays. My nested documents look like this: { '_id' : 1234, 'bio' : { ...

I am aiming to display the information received from my socket event in an ajax datatable

Utilizing socket to receive JSON data from the backend, I have the DATA variable containing the information I want to iterate into the AJAX data table. Below is the code snippet I am using: ` socket.on('getinvoices', (data) => { ...

Tips for uploading a file and submitting form data with Angular2, using [(ngModel)], and then storing the reference in MongoDB

Currently, I am working on a task page and I need to implement the functionality to upload a file along with the form submission to the NodeJs express server. @Component({ selector: 'tasks', template: `<div mdl class="mdl-grid demo-c ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

Having trouble receiving a Java Response through Ajax when using dataType: "jsonp", but it works when using dataType: "text"

I am having trouble retrieving the Callback response value in ajax with the provided code snippet $.ajax({ type: 'POST', jsonpCallback: 'jsonCallback', contentType: 'application/json', url: apiurl, dataTyp ...

Steps on incorporating fresh data into JSON format

pin = [ { "id": 26, "comments": [ { "id": 2, "username": "user", "description": "example", "pin": 26, "commenter": 1 }, ...

How to efficiently flatten an array in MongoDB using the aggregate framework

I have a collection of documents below and I was attempting to group and concatenate the site + items keys to create an array. However, using the map function results in each output being returned as an array. The final output under siteitems ends up as a ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

The iFrame is set to a standard width of 300 pixels, with no specific styling to dictate the size

My current challenge involves utilizing the iframe-resizer package to adjust the size of an iframe dynamically based on its content. However, even before attempting any dynamic resizing, I encounter a fundamental issue with the basic iframe: it stubbornly ...

Activating the spinner functionality using JavaScript

Having trouble activating the spin button with JavaScript for my spinner. Any ideas on how to make it work? <!DOCTYPE html> <html lang="en"> <head> <title>My Spinner</title> <link rel="stylesheet" ...

Convert an array of objects containing key-value pairs into fields named 'keyname' with their respective values using MongoDB

The current arrangement of my mongodb data appears as follows: { "_id": "5c9376110a32bd172c0c5a28", "timestamp": 1553168075444, "content": [ { "name": "temperature_x", "value": 2 }, { "name": "temperature_y", "val ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...