Attempting to create a recursive asynchronous search function in JavaScript

Currently, I am in the process of developing a code that involves searching through numerous objects stored in a MongoDB database. The main objective is to retrieve these objects based on their respective IDs and then further investigate the ID references within each object. Essentially, the program needs to focus on locating a specific ID by initially fetching the object related to that ID, followed by exploring the associated IDs within the object.

async function objectIdentifier(ID1, ID2, depth, previousList = []) {
    let pathway = []
    if (ID1 == ID2) {
        return [ID2]
    } else {
        previousList.push(ID1)
        let obj1 = await findObjectByID(ID1)
        let connectedID = obj1.connections.concat(obj1.inclusions) //creates an array comprising both object references and referenced objects
        let mapPromises = connectedID.map(async (id) => {
            return findID(id) //async function
        })
        let fulfilled = await Promise.allSettled(mapPromises)
        let list = fulfilled.map((object) => {
            return object.value.main, object.value.included
        })
        list = list.filter(id => !previousList.includes(id))
        for (id of list) {
            await objectIdentifier(id, ID2, depth - 1, previousList).then(result => {
                pathway = [ID1].concat(result)
                if (pathway[pathway.length - 1] == ID2) {
                    return pathway
                }})
        }
    }
    if (pathway[pathway.length - 1] == ID2) {
        return pathway
    }
}

I am exploring ways to enhance my code so that it functions similar to a tree search method, where each object and its corresponding ID represent individual nodes within the search structure.

Answer №1

I didn't delve too deeply into your code because I firmly believe in leveraging the power of your database whenever possible to do the heavy lifting.

In this scenario, MongoDB offers the $graphLookup aggregation stage for recursive lookups. Here's a brief example demonstrating how to utilize it:

db.collection.aggregate([
  {
    $match: {
      _id: 1,
      
    }
  },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$inclusions",
      "connectFromField": "inclusions",
      "connectToField": "_id",
      "as": "matches",
      
    }
  },
  {
    //additional pipeline steps might be necessary to revert back to original structure
    $addFields: {
      matches: {
        "$concatArrays": [
          [
            {
              _id: "$_id",
              inclusions: "$inclusions"
            }
          ],
          "$matches"
        ]
      }
    }
  },
  {
    $unwind: "$matches"
  },
  {
    "$replaceRoot": {
      "newRoot": "$matches"
    }
  }
])

Mongo Playground

If you prefer to keep this logic within your codebase, perhaps consider revisiting your for loop:

for (id of list) {
    await objectFinder(id, ID2, depth - 1, previousList).then(result => {
        route = [ID1].concat(result);
        if (route[route.length - 1] == ID2) {
            return route;
        }
    });
}

A cursory examination suggests that the line

route = [ID1].concat(result);

is being executed multiple times at the same level. Additionally, there seems to be confusion with your return statements towards the end of the function.

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

Mastering the Art of Incorporating jQuery, JavaScript and CSS References into Bootstrap with ASP.NET WebForms

Hey there, I'm currently working on a personal project as a beginner in Bootstrap. My main challenge for the past two days has been trying to integrate a dateTimePicker and number Incrementer using Bootstrap techniques. Despite my efforts in researchi ...

Principles for Designing Classes in PHP Using MongoDB

Working on developing an API has been an ongoing project for me. Starting with a concept last year, I have been dedicated to its development ever since. Throughout the year, the structure and offerings of the API have evolved significantly, making it chall ...

Selecting the content within a table to easily edit it

I am working on a project where I have a table filled with data fetched from a database. My goal is to allow users to click on a cell in the table, make changes to its content, and then save those changes back to the database. Below is the code snippet I a ...

Using Javascript to convert HTML tables (with CSS) into PDFs

I have a report presented in the form of an HTML table that is quite large, causing the browser to create a scroll in the x-axis. It becomes necessary for me to scroll or zoom-out in order to view the entire table. My goal is to utilize Javascript to conve ...

Utilizing PHP for XML exportation and fetching it through AJAX to integrate it into the DOM, unfortunately, the XML content remains invisible

I've encountered a strange issue with a PHP script that generates valid XML output. I'm trying to fetch this data using an Ajax XMLHttpRequest call in the browser. Although Firebug confirms that the Ajax request is successful and the XML is vali ...

What is the best way to calculate the total of elements from multiple arrays of various lengths using Javascript?

Is there a way to modify the code below to allow for adding an arbitrary number of arrays as arguments? For instance, how can I adjust it so that ([1, 2, 3], [4, 5], [6]) would result in an array of [11, 7, 3]? function addArrays(...arrays) { let resu ...

Using jQuery, generate a dynamic form to create a multidimensional array

I've set up a form where additional dropdowns can be dynamically added if the user clicks on a specific link. Here's an example of how it looks: <div class="dynamic-sale"> <select name="sizes[]" id="sizes" class="entry-dropdown"&g ...

A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected. I attempted binding the cl ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

Embedding links in v-bind:href

I inserted a dynamic link inside the <header></header> section using the method mentioned here: Vue JS and appending a variable to end of a URL Below are the relevant codes: <tr class="notice-row" v-for="(myCase, id) in case ...

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

Calculating the Mean of an Array in JavaScript

Greetings! I am working with an array that has the following structure: [ { group: "23", delays: [ { Station: "a", Arrival: "3", Departure: 0 }, { Station: "b", Arrival: -179, Departure: 0 }, ...

Pymongo: Best Practices for Connecting and Reading Data from Specific Hosts in a Replica Set, with an Emphasis on SECONDARY Servers

Context In a mongoDB production cluster with 3 hosts (non-sharded) belonging to replica set rs0, the setup is as follows: H1 - Primary H2 - Secondary H3 - Secondary An issue arose when attempting to create a python script using pymongo. To ensure minim ...

Error in syntax: missing comma after property identifier in MongoDB shell at line 4, position 5

Having trouble with a syntax error Getting error message "missing after property id@shell:4:5" db.movieDetails.updateOne({ title:"The Martian" } , { $set { poster:"http://howle.jpg" } }) db.movieDetails.updateOne({ title ...

Fill in the form using JSON data by matching the names with their corresponding values

Here is how I am collecting and storing the data from my web form as JSON, utilizing the name attribute and values. What is the best way to populate the form again with the saved JSON data in the same structure using name and value? (context: I will keep ...

Trouble with a basic array duplication function

function duplicateArray(arr) { var len = arr.length; var dup = new Array(); var j; for (j = 0; j < len; j++) { dup[j] = arr[j]; } console.log(dup); } return; duplicateArray([2, 3, 5]); I appreciate your assistance, There are no errors ...

AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets. controller.js crtPromoCtrl.controller(& ...

Is there a way to make a link clickable but also prevent another link from being activated when clicked?

Have you ever utilized #link to navigate to a specific section on a webpage? You can also incorporate animate and scrollTop() to ensure a smooth scroll. However, when the #link (Hash link) is situated in the navigation menu, it must be structured as exampl ...

Utilizing Moment.js: Transforming 12-hour format to a Date object

Is there a way to convert a 12-hour string into a 24-hour Date object? day.from = day.from || moment("6:00", ["h:mm"]).format("HH:mm"); Unfortunately, I am encountering the following error: angular.js:11706 Error: [ngModel:datefmt] Expected `6:00` to be ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...