angular-ui-tree, dynamically generate the tree using data retrieved from the DATABASE

I have implemented the angular-ui-tree library to present the folder hierarchy.

The nodes are saved in a MongoDB database, with each node object structured as follows:

{
   "node_name" : "Folder 1",
   "node_path" : "AAABBB",
   "node_id" : 103,
   "node_parent_path" : "AAA",
   "node_parent_id" : 13,
   "template" : "Template 1"
}

The Angular-UI-TREE is populated like this:

data = [
    {
        "node_name": "Folder 1",
        ...
        "nodes": [
            {
                "node_name": "Folder 1-1",
                ...
                "nodes": [
                    {
                        "node_name": "Folder 1-1-1",
                        ...
                        "nodes": []
                    }
                ]
            },
            {
                "node_name": "Folder 1-2",
                ...
                "nodes": []
            }
        ]
    },
    {
        "node_name": "Folder 2",
        ...
        "nodes": []
    }
]

Using this structure, the tree will display folders and subfolders similar to:

Folder 1 
|
---> Folder 1-1
     |
     ---> Folder 1-1-1
|
---> Folder 1-2
Folder 2

Given the nodes stored in MongoDB following the specified schema, I aim to populate the DATA array for building the UI tree. What would be the most efficient approach to achieve this?

Alternatively, is there a better way to organize and store these nodes in the database to simplify retrieving the information required to build the tree?

Answer №1

It's difficult to determine the server language you're using, so I'll provide a general approach.
You have two main options: either implement a recursive query or construct a nested list from a flat list.

1) Recursive Query: Develop a function that retrieves all child nodes of a given node, identifies the root node, and appends the results as child nodes to the original node. Execute the recursive query function on each returned result to create the desired structure starting with the root node.

2) Associative Array: Retrieve all nodes from MongoDB and organize them in an associative array indexed by the node paths. Traverse this array and append each item to the 'nodes' list of its parent node using the parent path as the key. Obtain the root node(s) by their paths from the associative array and assign them to the 'data' array. Optionally, establish double links to enforce the parent reference.

In option 1, consider creating a placeholder for the root node if it is actually a list. For option 2, scan through all items in the associative array to identify those without a parent node and form your base root list. Feel free to ask any additional questions for further clarification.

Best of luck!

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

Generating binary payload with Node-RED

Recently started with node-red and javascript. I am looking to establish a connection with a relay controller for status using the TCP input. I have configured a function node to create a two-byte request which will be sent through the TCP input node to th ...

Using Vue to iterate through elements

I am struggling to loop through an array in a Vue component without duplicating the element specified in the 'v-for' directive. I have consulted the official Vue.js API documentation, as well as various online articles, but haven't found a s ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

Unable to render a rectangle with React's canvas context.fillRect

Could anyone help me with drawing a rectangle using React? I'm having trouble getting it to work. I'm confused as to why the code below isn't showing a rectangle on the screen. class DrawingView{ constructor(props) { this.canva ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

I am attempting to locate a specific char[] within a two-dimensional char array and store the value of the index n where it was found

I am attempting to iterate through fooArray to search each entry for foo and then increase fooCount in the appropriate entry. Currently, I can successfully input the string "H A P Y \0" into both foo and fooArray[2], yet the evaluation fooArray[2] == ...

Can you please provide the appropriate PropTypes for a dictionary in a ReactJS project?

Looking for something along the lines of y = {"key0": [value0, value1], "key1":[value2]} What is the proper way to define the proptypes for y? ...

Unique: "Unique One-Step Deviation in Date Comparison"

A Little Background Information: I am working with data points that span from the current day to 5 days ahead, in 3-hour intervals (such as 10pm, 1am, 4am, 7am...). My goal is to organize these data points into arrays sorted by date, with each array repre ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

Highcharts displaying black color after AJAX refresh

Struggling to implement real-time data visualization using Highcharts, I found myself tired of sifting through documentation and feeling confused. My solution involves using AJAX refresh. When the page initially reloads, my chart renders properly. However, ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

The selected attribute does not function properly with the <option> tag in Angular

Currently, I am faced with a challenge involving dropdowns and select2. My task is to edit a product, which includes selecting a category that corresponds to the product. However, when I open the modal, the selected group/category is not displayed in the d ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...

What is causing the delay in retrieving elements using getX() method in Selenium?

Recently, I've been experimenting with web scraping using Selenium. However, I've noticed that there is a delay when calling getText(), getAttribute(), or getTagName() on the WebElements stored in an ArrayList from the website. The website I&apo ...

problem with transmitting information through $.ajax

I'm facing a frustrating issue with the $.ajax()... function in my PHP code. I am unable to retrieve the data sent by the ajax request. <?php if ($_POST){ include 'Bdd_connexion.php'; $filiere = $_POST['filiere']; ...

Perplexing behavior displayed by non-capturing group in JavaScript regular expressions

Here's a straightforward question for you. Regex can sometimes get tricky, so thank goodness for simplifying things... In the URL, there's a query parameter labeled ?id=0061ecp6cf0q. I want to match it and only retrieve the part after the equal ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...