0

how can i make a assign mongoose result in local variable in node js? I want to add my sum of monthlyorder in local variable and print outside find function.

var monthlyOrders;
var monthlyExpense;
var Profit_month;

CompleteOrders.find({
  CompleteDate: {
    $gte: startDate,
    $lte: endDate
  }
}, function(err, data) {
  if (err) next(err);
  var monthlyOrder = lodash.sumBy(data, function(o) {
    return o.Total;
  });
  monthlyOrders = monthlyOrder;
  res.locals.income = monthlyOrders;
});

Expense.find({
  ExpenseDate: {
    $gte: startDate,
    $lte: endDate
  }
}, function(err, data) {
  if (err) next(err);
  monthlyExpense = lodash.sumBy(data, function(o) {
    return o.Expense;
  });
  res.locals.Exp = monthlyExpense;

});
console.log(monthlyExpense);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    Duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Samathingamajig Aug 11 '22 at 20:28
  • You defined `monthlyOrders` outside of your find. If you remove the `var` where you assing a value to `monthlyOrders` inside the find, it should assign the value to the outside `MonthlyOrders` variable instead of creating a new local one with the same name. – Prdufresne Aug 11 '22 at 20:34
  • 1
    @Prdufresne the local variable is called `monthlyOrder` whereas the global variable is called `monthlyOrders` so it's not the same name. And even if it was, it still wouldn't work, because the real problem is that OP isn't awaiting the async call ... – derpirscher Aug 11 '22 at 21:52
  • Oh yeah. You're right, I didn't see difference there. I guess it makes sense that `find` would return a promise. – Prdufresne Aug 12 '22 at 12:39

0 Answers0