"Linking and accessing data from different collections in MongoDB to enhance overall

Extracting information from an external API provides me with two separate data sets: one for football matches and another for football competitions. I store this information in MongoDB. Inquiring about a specific football match, I am interested in knowing the standings of each team within the associated competition.

Below are the models being used:

Game

{
    ...,
    homeTeam: {
        id: 1234
    },
    awayTeam: {
        id: 2345
    },
    ...
}

Competition

{
    ...
    standings: [
    {
        position: 1,
        team: {
            id: 1234,
            ...
        },
        ...
    },
    {
        position: 2,
        team: {
            id: 2345,
            ...
        },
        ...
    }
    ]
}

I attempted using aggregation with $lookup but encountered challenges getting it to perform as desired.

const game = await Game.aggregate([
        {$match: {'competition.id': parseInt(req.params.id)} },
        {$lookup: {
            from: 'competitions',
            localField: 'homeTeam.id',
            foreignField: 'standings.team.id',
            as: 'homeTeam.position',
        }}
    ]);

The expected outcome for each game is represented below:

{
    ...,
    homeTeam: {
        id: 1234,
        position: 1
    },
    awayTeam: {
        id: 2345
        position: 2
    },
    ...
}

Answer №1

Here's a method using forEach and an if statement to achieve the desired outcome. The code is well-commented for clarity, and any questions you have can be addressed by asking.

let objectsArr = Object.keys(firstOBJ); // extracting properties
let answer = []; // creating a new array for the answer
let childs = Object.keys(secondOBJ); // getting properties of secondOBJ
secondOBJ[childs].forEach((val, i) => { // iterating through properties of secondOBJ
  if (firstOBJ[objectsArr[i]].id == val.team.id) { // comparing id's before proceeding
    name = objectsArr[i]; // storing the name
    answer.push({ // pushing data along with the name
      [name]: {
        id: val.team.id,
        position: val.position
      }
    })
  }
});

Test snippet provided below for verification:

let firstOBJ = {
  homeTeam: {
    id: 1234
  },
  awayTeam: {
    id: 2345
  }
}
let secondOBJ = {
  standings: [{
      position: 1,
      team: {
        id: 1234,
      },
    },
    {
      position: 2,
      team: {
        id: 2345
      },
    }
  ]
}
let objectsArr = Object.keys(firstOBJ);
let answer = [];
secondOBJ[Object.keys(secondOBJ)].forEach((val, i) => {
  if (firstOBJ[objectsArr[i]].id == val.team.id)
    answer.push({
      [objectsArr[i]]: {
        id: val.team.id,
        position: val.position
      }
    });
});
console.log(answer)

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

Removing an item from a Firebase array: A step-by-step guide

I'm currently facing a challenge with removing a specific object/field within a document in Firebase. While I can delete entire collections or documents, I'm struggling to delete the name and tag fields associated with a particular ID. Is there a ...

What is the best way to loop through arrays of objects within other arrays and delete specific attributes?

I have an array of JavaScript objects with potential children who share the same type as their parent. These children can also have their own set of children. My goal is to loop through all nodes and modify certain values. [ { "text": "Auto", ...

Updating front end data using Node.js - A Comprehensive Guide

I am looking to create a website using node.js that can dynamically display a plot and update the data every minute without needing to refresh the entire page. As someone new to node.js, I am interested in learning how to use "get" requests to update the d ...

The homepage was updated following the click of the "Home" link

In the process of building a personal blog, I decided to use node.js, express, and angular.js. The index page contains a link labeled <a href="/">Home</a>. This link is present in the layout.jade file as shown below: Initially, everything seem ...

Using a node module for Three.js path manipulation

Currently, I am in the process of learning Three.js and have set up a basic project that runs on a node.js server while importing Three.js as a node module. Although my setup is working fine, I find myself a little bit confused about whether this is consi ...

From jQuery to Vanilla JavaScript: Implementing a simple click event listener

I've been attempting to translate the following jQuery code into vanilla JavaScript, however, I can't get it to function properly. jQuery: $(document).ready(function() { $("button").click(function() { var char = "0123456789abcdefghijklmno ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

The 'command cursor' object cannot be accessed using square brackets

Currently diving into the world of Python and MongoDB, I am embarking on a new project utilizing flask-python and MongoDB. However, when attempting to retrieve data using the aggregate() function, I encountered the following error: command cursor' ...

Passing a number instead of a string in Reactjs onClick for the <MenuItem> element

Using material-ui in ReactJS, the code below showcases a sidebar function for filtering product information. The sidebar includes two filters: size and color. Clicking on the Expansion Panel reveals options, but when selecting a color, the colorReducer fun ...

Handling onChange events for several typescript <Select> elements

As a non-TS developer, I'm delving into the realm of multiple selects and dropdown menus with Material-UI's select component. Progressing from a basic setup, I successfully implemented a single select but now face a challenge in adding another dr ...

Struggling to retrieve a particular user using ExpressJs due to an error

Looking to retrieve a specific user in ExpressJS from a JSON file. Encountering this error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This is the snippet of code being u ...

What is the best way to access a JSON object obtained through AJAX within the DOM?

My sinatra app is fetching data from an API using ajax jsonp. I am able to see the returned json in the console, but I'm unable to access it from the DOM where I need it to populate a table. I tried adding it as an HTML5 data-attribute, but unfortunat ...

When extracting a value from an HTML textarea that contains multiple lines of text inputted by the user, the JSON becomes invalid

Here is the JSON format I am working with: { questionID: int studentAnswer: "String" } The issue I am facing is that the studentAnswer field is currently only capable of holding input from a single line in an HTML textarea. If I input text that spa ...

Javascript Pretty Print Format is producing inaccurate output

function displayData(info) { document.body.appendChild(document.createElement('pre')).innerHTML = info; } function searchInGitHub(str) { const http = new XMLHttpRequest(); http.open("GET", "https://api.github.com/search/reposi ...

Interactive marker popup appearing beyond the boundaries of the map container

Our popups are set to display outside of the map container initially, but when the map is moved, they adjust to fit inside the container with the correct anchor. However, upon inspecting the DOM, we noticed that the popups do not always have the correct an ...

Explore the wonders of utilizing MongoDB in conjunction with Node.js

I am attempting to execute a query on MongoDB and log some data to the console. The MongoDB collection I am referencing is named 'data', and the cluster is labeled 'stocks'. While I have been able to populate the MongoDB database using ...

Tips for resolving the "Unexpected reserved word" error during the installation of Laravel Jetstream

I have been following the steps outlined on to set up Laravel Jetstream. Upon running artisan jetstream:install, I selected Livewire support, API support, email verification, and PHPUnit support for installation. Next, I executed npm install as per the ...

I require my two elements to possess opposing transformations in their coordinates or directions to enable dragging capabilities

Changing the code to move the elements in opposite directions is my goal. I attempted multiplying the second element by -1, but unfortunately, I keep ending up with a NAN or undefined result. Any suggestions on how to achieve the desired effect? ...

Display a dialogue box in close proximity to a text area without utilizing a pop-up or alert notification

How can I display a short message next to a textarea when it is clicked? Below is the code that needs modification: <textarea id="txt" ></textarea> and : $('#txt').click(function(){ // What should be added here to show a dialog bo ...

calls for angular http.get within other angular http.get calls

I am working on a basic angular $http.get request that returns a json object. What I need is to extract the id from the response and use it for another $http.get call. The solution I have in place involves nesting another $http.get within the first one, ...