Delays using multiple for loops I got this script which work perfectly but I got some delays because of this 2 for loops [i][j] is there any way to do the same function but with a better and effective process like foreach or other.

User.find({}).lean(true).exec((err, users) =&gt; {
        let getTEvent = [];
        //nested loops() //callbacks

        for (let i =0 ; i &lt; users.length; i++) { 
          if(users[i].events &amp;&amp; users[i].events.length) {
const dt = datetime.create();
dt.offsetInDays(0);
const formatted = dt.format('d/m/Y');
// console.log(formatted)
for (let j = 0; j &lt; users[i].events.length; j++) {
    if(users[i].events[j].eventDate === formatted) {
      getTEvent.push({events: users[i].events[j]});
      }  
    }
  }
}


   return res.json(getTEvent)
    }); 


The main role of this code is: 


find the data in Mongodb: find all users with or without events
loop through data and select events made by any users
push the results in an array which is getEventin order to be useful later for the client side


Details:

The User is the model: const User = require('../models/users.model');
and events is [] array.

This is Mongodb structure of that models:
I think the main cause of your delays is not a nested for but rather a fact that you extract all data from your mongodb collection into memory. What you can do is


You can calculate formatted date once.
Then you can query just those users that contain given event date instead of populating all users in memory. Here's the guide


This will look roughly like the following

const dt = datetime.create();
dt.offsetInDays(0);
const formatted = dt.format('d/m/Y');

User.find({
        "events": {
            eventDate: formatted
        }       
    }).lean(true).exec((err, users) =&gt; {
        let getTEvent = [];
        //nested loops() //callbacks

        for (let i = 0 ; i &lt; users.length; i++) { 
          if(users[i].events &amp;&amp; users[i].events.length) {           
            for (let j = 0; j &lt; users[i].events.length; j++) {
                if(users[i].events[j].eventDate === formatted) {
                  getTEvent.push({events: users[i].events[j]});
                }  
            }
          }
        }


   return res.json(getTEvent)
});