My goal is to make multiple asynchronous requests to Mongo using Mongoose in parallel. To achieve this, I created a helper function that handles these queries dynamically without knowing the exact number beforehand. While my current implementation works well, I have some reservations about the use of eval in my code. The issue arises when I try to execute the eval(return${returnStr}) statement and it results in a SyntaxError.
const batchRetrieve = async (query, models) => {
models.forEach((model, i) => {
eval(`task${i} = ${model}.findOne(query)`);
});
let str = [];
for (let i = 0; i < models.length; i++) {
str.push(`res${i}: await task${i}`);
}
const joinedStr = Array.prototype.join.call(str, ', '); //output is 'res0: await task0, res1: await task1'
// return { res0: await task0, res1: await task1 }; works fine
eval(`return { ${joinedStr} };`);
};