0

I simplified the problem as I could.

            Transaction.find({budget: foundBudget._id}, function(err, foundTrans) {
              if (err) console.log(err);
              else {

                uniqueUsers = foundTrans
                .map(user => user.who)
                .filter((value, index, self) => self.indexOf(value) === index)
                
                console.log(uniqueUsers);


                uniqueUsers.forEach(function(user, i) {

                  console.log("foundBudget._id " + foundBudget.id);
                  console.log("user " + user);

                  Transaction.find({budget: foundBudget._id, who: user}, 'amount')
                  .exec(function(err, amountsInTrans) {
                    if (err) console.log(err);
                    else  console.log("Here");
                });

                });

                console.log("Here2");

                
              }
            }); 

It won't go into the second Transaction.find() query's callback function.

console.log(uniqueUsers); logs [ 'Aras' ], simply because that's the only user.

console.log("foundBudget._id " + foundBudget.id); and console.log("user " + user); logs

foundBudget._id 5f77b8971fd44e456c8145d7
user Aras

and the related schema is like this,

const transactionSchema = new mongoose.Schema({
  who: String,
  amount: Number,
  info: String,
  budget: String
})

So, the query should work and it should go into the callback function but I'm not getting a log from console.log("Here");, I'm only getting Here2. Any ideas?

  • Are you sure this is the correct syntax? `Transaction.find({budget: foundBudget._id, who: user}, 'amount')` I'm not sure what you are trying to do with `'amount'`. Also instead of `exec` why not stick with the callback syntax you have for the first `find()`? – dwosk Oct 03 '20 at 00:32
  • I'm normally using the first syntax at the top but since that didn't work, I started trying other syntaxes that I found on mongoose documentation. None of them worked. 'amount' gets only the amount of transactions. It doesn't work with it or without it. I've been trying to solve this for a few hours. – Aras Uludağ Oct 03 '20 at 00:36
  • remove "amount" as the second parameter and see if that works. See this as an example for `.exec()`: https://stackoverflow.com/questions/31549857/mongoose-what-does-the-exec-function-do – dwosk Oct 03 '20 at 00:38
  • I finally found out what was the problem. Apparently Mongoose find queries doesn't put the code in hold. The code continues executing before actually finishing the query itself. When the code finishes to compile, it's too late. Query didn't even reach the callback and that's why I got an error. The solution is to move everything into the query's callback, so the code cannot continue executing before finishing the query. – Aras Uludağ Oct 03 '20 at 11:04

0 Answers0