So i am trying to find an opponent for user based on his trophies, it works fine when if condition isnt run but when if condition runs, it runs infinte 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 }```
If it's infinite looping, it seems that your aggregation keeps pulling the same user as 'user.id', which recursively calls the matchmake function again over and over.
I would try to add a $not condition to your match that checks for the user.id. That way, the aggregation doesn't return the original user.