In the process of developing a matchmaking feature

Currently, I am working on a matchmaking system to find suitable opponents based on a user's trophies. Everything seems to be working fine until the if condition is triggered, which results in an infinite loop.

const UserProfile = require("../schemas/userProfile")
async function matchmake(user, message) {

   let UserProfileDetails = await UserProfile.findOne({ userID: user.id });
   let userTrophies = UserProfileDetails.trophies;

   let userMatched = await UserProfile.aggregate([
      { $match: { trophies: { $gte: userTrophies - 10, $lte: userTrophies + 10 } } },
      { $sample: { size: 1 } }
   ]);

   let otherUserID = userMatched[0].userID;
   console.log("userID -"+otherUserID);
   if (otherUserID === user.id) {
      otherUserID = await matchmake(user, message);
   }
   return otherUserID;
}

module.exports = { matchmake }

Answer №1

When trapped in an endless loop, it appears that your aggregation is repeatedly fetching the same user as 'user.id', causing the matchmake function to be called recursively without end.

To break this cycle, consider incorporating a $not condition into your match query to exclude the user.id from being returned in the aggregation results.

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

Using `getJson` to parse the tree structure

I am currently working with a JSON file that contains order data. The structure of the JSON file is as follows: { "orders": [ {"name": "Peter", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64140110011624050b0 ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

Deactivate text/input field in React and Next.js based on Dropdown Selection

As a newcomer to React, I am facing an issue with disabling and enabling an input field based on the selected value in a dropdown. My tech stack includes React, Next Js, React-bootstrap, and formik. function Input(){ const [disabled, setDisabled] = useStat ...

The jQuery code does not execute following the use of window.location.replace( url ) command

I'm facing an issue with my code that involves redirecting the page to the index page after clicking on a specific link ('#versionPageFromProdLink'). The index page contains certain content within a div, which I want to hide once the redirec ...

Support for time-series data in MongoDB through ingestion from Debezium

My server receives data from multiple devices generated by their sensors. This telemetry data is stored in json format in a partitioned table named statuses in a postgresql database. The table is partitioned monthly on the columns time_stamp and device_id, ...

Switch Background Image - The image failed to display

Here is the code snippet I am currently working with. It involves displaying a background-image when clicking on a link with the class 'home-link', and not showing an image if the link does not have this class. The issue at hand: The problem ari ...

Vue router is unable to render or mount the component at the root path

I am currently working on a webpage using vue, vue-router, and laravel. I have encountered an issue where the Home component is not being rendered in the router-view when I access localhost/myproject/public_html/. However, if I click on the router link to ...

experiencing a fault in the Magento platform

Every time I visit my website, I am faced with the following issue (I retrieved this error file from the var folder): a:5:{i:0;s:88:\"Cannot send headers; headers already sent in /home/eyewear/public_html/index.php, line 1\";i:1;s:943:\"# ...

Dispatching $emit / $broadcast events from multiple areas of the code and capturing them in a single location

I have a practice of sending $emits (or $broadcasts) from various parts of the code and different controllers, but intercepting them all from one centralized place. While this approach seems to be functioning properly, I am unsure if it may be considered b ...

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

Setting up lint-staged for Vue projects: A step-by-step guide

After setting up a new Vue3 app using the Vue CLI and configuring Prettier as my linter, I decided to implement commitlint, husky, and lint-staged for validating commit messages and linting the code before pushing it. My Approach Following the instructio ...

Troubleshooting: Issue with passing variables from jQuery $.ajax to PHP

I am working on creating a 'show more' button using jQuery AJAX. The button has a loaded attribute like this: <button type="button" class="smbt btn center-block" data-loaded="3">Show More</button> In my JavaScript file, I have the f ...

Retrieving the sub-document with the minimum value in MongoDB

Provided with the following data... { "_id": ObjectId("56116d8e4a0000c9006b57ac"), "name": "Stock 1", "items" [ { "price": 1.50, "desc": "Item 1" } { "price": 1.70, "desc": "Item 2" } { "price": 1.10, "desc": "Item 3" } ] } I am aiming to r ...

In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am us ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

Transmitting a Wav file from JavaScript to Flask

I'm currently working on a JavaScript code that records audio from the browser and now I need to figure out how to send it back to Flask. start: function () { var options = {audio: true, video: false}; navigator.mediaDevices.getUserMedia(optio ...

The callback for fs.WriteFile is triggered before the file is written to disk

I am encountering an issue with my express request callback that involves writing a file after calling a callback function. zip.addLocalFolder(`/path/to/folder`, `./`); var data = zip.toBuffer(); fs.writeFile(`path/to/download.zip`,data,function (err) { ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Steps to activate the "ReST API" feature on mongodb-org version 4.4.4.1

Currently, I am using version 4.4.4-1 of the mongodb-org edition, which is one of the latest versions available at the moment. I seem to be having trouble locating where I can activate its ReST API interface. It appears that the --rest option is not accep ...

How to insert a row above the header in an Excel sheet using JavaScript within

i am using excel js to export json data to excel. The json data is successfully exported to the sheet, but now I need to add a row that provides details of the sheet above the header text. for more details please refer image the code is shown below: i ...