Empty results received from MongoDB queries executed within an asynchronous loop

I'm encountering an issue where I have a list of IDs that I need to query Mongo with in a for loop, but it always returns an empty []. Initially, the queries were returning promises, so I switched from using forEach to a standard for loop as shown here and also tried using toArray(), both of which resulted in an empty [].

async function queryRoles(id) {
    const db = await connectToMongo()
    let response;
    try {
        response = await db.collection("permissions").find({"_id": xxx}).toArray();
        console.log(await response);
    } catch (error) {
        console.log(error);
    }
    return response;
}

async function checkAuthorisation(list, groups) {
    for (const item of list) {
        const index = list.indexOf(item);
        const rolesList = await queryRoles(item._id);
        console.log(rolesList);
    };
    }

The rolesList is consistently empty and does not populate with any data.

Strangely, when I execute the same query for a single mongo document without using the for loop, I receive the expected response, confirming that the connection to MongoDB is functioning correctly.

What could be going wrong here? It's getting frustrating trying to figure this out!

Answer №1

Were you able to experiment with this method?

  async function checkAuthorization(list, groups) {
    const roleList = await Promise.all(
      list.map(async (item, index) => 
        await queryRoles(item._id)
      )
    );
    ...
  }

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

The download attribute in HTML5 seems to be malfunctioning when encountering a 301 Moved Permanently

I am attempting to create an automatic download feature for a file from a URL with a 301 Moved Permanently redirection. Here is the current code: <a href="myserverapi/download?fileId=123" download="image.jpg" target="_blank" ...

Creating a JSON File with an Illustrator Script

Currently, I've been working diligently on developing a system that allows me to export my swatches from Illustrator as a JSON object. This will greatly simplify the process of updating my App. By utilizing the illustrator scripting API, I've suc ...

Retrieving column values from a Datatable is limited to the first 10 rows

Trying to extract the values from column 1. I followed the instructions provided in the datatable documentation: var data = table.column( 0 ).data(); Table setup: var datatable = table.dataTable({ "scrollX" : "100%", "scrollY" ...

What is the meaning behind the term KOA2 that people are referencing?

Can anyone explain the relationship between KOA and KoA2 in NPM? I've been trying to work with the KOA framework and I'm unsure whether to use KOA or KoA2 from the code repositories on NPM. Is Koa2 referring to KOA 2.x or a different package alt ...

Error: The field "key" must be provided

Encountering an error with express-openid-connect TypeError: "secret" is required at module.exports.get (/home/mathkr/persodev/node_modules/express-openid-connect/lib/config.js:166:11) at module.exports (/home/mathkr/persodev/node_modules ...

When the specified width is reached, jQuery will reveal hidden circular text upon page load instead of keeping it hidden

My current issue involves utilizing jQuery to hide circular text when the window width is below 760px. Although the functionality works as intended, there is a minor problem when the page loads under 760px width - the text briefly shows up before hiding ag ...

Even when it appears to be chaotic, the TypeScript array of numbers always manages to find its way back to being sorted

I recently developed a function that aims to verify if an array of numbers is sorted: const checkIfSorted = (numbers: number[]) => { return numbers === numbers.sort((a, b) => a - b); }; checkIfSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // This cur ...

Updating a validation directive on $watch in AngularJS version 1.2

I created a directive for validation on a multi-select that allows for dynamic length validation of selected items. The directive is used like this: (function() { 'use strict'; angular .module('myModule') .dire ...

Divide a string into an array starting from the end

I have a unique phrase. var phrase = "LoremipsumdolorsitametconsectetuadipiscingelitSeddoeiusmodtemporincididuntutlaboreetaliqua"; I am interested in dividing it into chunks of 11 characters starting from the end. Currently, I use: function splitPhrase ...

Tips for excluding certain parameters in the jslint unparam block

While developing my angular app, I encountered an issue with jslint flagging an unused parameter. Typically in angular, the "$scope" is required as the first parameter in your controller definition. In my case, I prefer using the "this" keyword instead of ...

The asynchronous method in a Mongoose schema does not pause for completion

Here is the code snippet that I am currently working on: const user = await User.findOne({ email }).select('+password'); console.log(' user value : ', user); const boolean = await user.comparePassword(password, user.password); console.l ...

Unable to access the URL slug within the client component in Next.js version 13

In my upcoming project with Next 13, I have a client-side component that is being rendered under the route /journal/[date] Unfortunately, I'm facing an issue trying to extract the date from the URL. I attempted to use: import { useRouter } from &apos ...

Prevent WARN and/or ERROR messages in npm

npm may generate errors and warnings during installation. Is there a way to turn off one or both of these notifications? ...

In React Native, the concept of "null" does not exist within component state as an

I'm currently working on integrating the react-native-modal-datetime-picker functionality into my application Code Snippet: import React, { Component } from "react"; import { View, ScrollView, DatePickerIOS, TouchableOpa ...

Can you provide guidance on decompressing SVGZ files using JavaScript?

I'm currently working on implementing a high-resolution world map using SVGZ instead of the standard SVG format, aiming to provide my users with a more intricate and detailed visualization. Although I have experimented with utilizing js-deflate to de ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

In ES6 React, if you want to add arguments to event handlers when functions are bound in the constructor, follow these

When working with constructors in es6, it is recommended to bind functions early like so: class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); // binding done in the constructor ...

Can you show me the steps to set a session in the front-end using Nuxt

I have successfully set the session using code on Postman. First: I set my session and it is functioning properly. const user = { name: 'afshin', }; req.session.user = user; res.status(200).send({data:req.session.user,status:200}); Second: No ...

Locating the source and reason behind the [object ErrorEvent] being triggered

I'm facing an issue where one of my tests is failing and the log is not providing any useful information, apart from indicating which test failed... LoginComponent should display username & password error message and not call login when passed no ...

We regret to inform you that the request cannot be processed by our Express

Currently, I am in the process of learning nodejs and expressjs and attempting to integrate it into the Spring MVC pattern. My intention behind this is to maintain cohesion within my files. However, the results are not quite aligning with my expectations.. ...