Exploring the ancestry of Mongo

I am currently working on constructing a family tree that can have an infinite number of levels for parents and children. I am also interested in finding relationships like brothers, sisters, cousins, and so on. However, I'm facing some confusion when it comes to creating an array in JavaScript based on data that only provides the parents of each person.

Within a MongoDB Collection named "Users," here are some of the entries:

{ id: 1, name: "Target", parents: [3,4] }
{ id: 2, name: "Wife" }
{ id: 3, name: "Dad", parents: [5,6] }
{ id: 4, name: "Mom" }
{ id: 5, name: "Dads Dad", parents: [7,8] }
{ id: 6, name: "Dads Mom" }
{ id: 7, name: "Dads Dads Dad", parents: 9 }
{ id: 8, name: "Dads Dads Mom" }
{ id: 9, name: "Dads Dads Dads Dad" }
{ id: 10, name: "Son", parents: [1, 2] }
{ id: 11, name: "Sons Son", parents: [10] }
{ id: 12, name: "Sons Sons Son", parents: [11] }
{ id: 13, name: "Brother", parents: [3,4] }
{ id: 14, name: "Brothers Son", parents: [13] }
{ id: 15, name: "Uncle", parents: [5,6] }
{ id: 16, name: "Aunt", parents: [5,6] }
{ id: 17, name: "Daughter", parents: [5,6] }

While I can easily loop through each child using their IDs and output them, it doesn't provide a structured view of children's children; instead, it just loops and outputs.

getChildren = function(id) {
    var children = Users.find({parents: id});
    children.forEach(function(child) {
        console.log(child);
        getChildren(child.id);
    });
};

I've been attempting to create two global variables called ascendants and descendants to organize parents, grandparents, etc., along with nesting their respective children inside (for siblings and nephews) and similarly for descendants. However, this has become complex due to multiple nests and the need to add entries within others.

If someone could assist me in structuring this information, I believe I could use it to create an HTML/CSS family tree. To handle non-parent/child relations, I may have to conditionally loop again?

descendents = {
    10: {           // son
        11: {       // grandson
            12: {}  // great grandson
        }
    },
    17: {           // daughter

    }
}

Answer №1

By maintaining your current structure and making a slight adjustment to your approach, you can identify the parents of a specific id as well as the children of a given parent id.

Define the variable root to store the resulting structure:

var root = {};

Here is the recursive function to retrieve all descendants:

var getDescendants = function(id, root) {
    var children = Users.find({parents: id});
    children.forEach(function(child) {
        root[child.id] = {"name": child.name};
        getChildren(child.id, root[child.id]);
    });
};

getDescendants(3, root);

Sample output:

> root
{
        "1": {
                "10": {
                        "11": {
                                "12": {
                                        "name": "Sons Sons Son"
                                },
                                "name": "Sons Son"
                        },
                        "name": "Son"
                },
                "name": "Target"
        },
        "13": {
                "14": {
                        "name": "Brothers Son"
                },
                "name": "Brother"
        }
}

Next, here is the recursive function to find all ancestors:

var getAscendants = function(id, root) {
    var rec = Users.findOne({id: id});
    if(rec.hasOwnProperty("parents")) {
        (rec["parents"]).forEach(function(parent) {
            root[parent] = {};
            getAscendants(parent, root[parent]);
        });
    }
};
var root = {};
getAscendants(12, root);

To retrieve non-children/parents, you may need to apply conditional logic.

A suggestion would be to utilize the $nin operator for this purpose.

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

Is there an issue with loading Vue list rendering due to Axios not returning the data?

Utilize the axios request api interface to fetch data and populate a list, but encounter a problem when trying to iterate through the properties of an object using v-for. Take a look at the javascript snippet below: var vm = new Vue({ el: '# ...

Error: An error occurred because the program attempted to read properties of a null value, specifically the property "defaultPrevented"

There seems to be an issue with a script error involving both the bootstrap alert and my own close alert tag. I have a script set up to automatically close alerts after 2.5 seconds when certain user actions trigger them, such as creating a blog post or del ...

React Image Slider not loading pictures

Can someone help me troubleshoot why my images are not displaying in the slider on my homepage? I have set up the slider using React Slideshow Image, but the images are not showing up for some reason. I am also wondering if anyone knows of any full-screen ...

Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next butt ...

Associating data with controller upon click event

My application displays a tab full of objects for the user to choose from by clicking on any line. Once they make their selection, I need to send specific data related to that object to the server. This is what the interface looks like: https://i.sstatic ...

Create a roster of individuals who responded to a particular message

Can a roster be created of individuals who responded to a specific message in Discord? Message ID : '315274607072378891' Channel : '846414975156092979' Reaction : ✅ The following code will run: bot.on("ready", async () = ...

"What's the best way to make sure a checkbox stays checked and its content remains visible after a

After updating my HTML content, it now consists of a hidden table inside a div with the class "myClass": <div class="myClass" style="display:none"> <table class="table table-hover"> ..... </table> </div> The table remains hidden u ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

What measures can be taken to restrict users from inputting decimal values?

My website includes an order page where users can input quantities for various items. While some items allow for decimal quantities, others do not. What is the most effective method to restrict users from entering decimal quantities? (Besides using an ale ...

Is there a way to attach a file in Mongoose Schema? I tried using String and it worked, but when I tried to use File, I encountered the error "[1]Error: File is not

const mongoose = require('mongoose'); const { Schema } = mongoose; const NoteSchema = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', }, title: { type: String, required: true, }, attac ...

Is it possible to employ a jQuery handler as the selector for the .on() method?

Can a jQuery handler $(...) be used as the selector for .on()? The code snippet below illustrates this: how can I change the circle's color to blue without having a plain text representation of my selector, but still using a handler? // This works. ...

How to send parameters through the Google Maps API URL using Vue.js

When using $router.push(), I receive two parameters: {{ this.$route.params.lat }} and {{ this.$route.params.lng }}, which are latitude and longitude coordinates. To access a Google Maps URL, I need to include both of these parameters: https://maps.googlea ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Moving Configuration Files in NextJS

When working on a typical Next.js project, I often end up with several root-level configuration files: tsconfig.json next.config.js next-seo-config.ts .eslintrc etc... I am looking to tidy up my root directory by moving these files into their own separat ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

JavaScript Truthy and Falsy Tutorial on Codecademy

Could someone kindly clarify why this code is not functioning correctly? let defaultName; if (username) { defaultName = username; } else { defaultName = 'Stranger'; } This code snippet was found in the JavaScript section on Codecademy, but a ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...

Utilize the useRef hook to dynamically retrieve the updated height when children are altered

I am working with an accordion component and using the useRef hook to measure the height of the children. However, I noticed that when I update the content of the children dynamically, the height measurement does not get updated unless I click on the toggl ...

Is there a way for me to determine the dimensions of the webcam display?

How do I determine the width and height of the camera in order to utilize it on a canvas while preserving proportions? I am attempting to ascertain the dimensions of the camera so that I can use them on a canvas. On this canvas, I plan to display live vid ...