Javascript 循环顺序。查找、收集并向前端发送大量数据。糟糕的方法?

Javascript 循环顺序。查找、收集并向前端发送大量数据。糟糕的方法?,javascript,mongodb,express,Javascript,Mongodb,Express,我正在使用express、react和MongoDB。我对express和restapi一无所知 我正在尝试为我的前端实现一个关于销售、订单等的分析部分。其想法是允许搜索一系列日期,其中每个对象都有一个日期戳,然后我在其中进行比较和收集 我的方法不起作用,allOrder似乎没有像我预期的那样收集所有对象 var allOrder = []; // gather all orders and push them do { Order.find({ date: sDate }) .t

我正在使用express、react和MongoDB。我对express和restapi一无所知

我正在尝试为我的前端实现一个关于销售、订单等的分析部分。其想法是允许搜索一系列日期,其中每个对象都有一个日期戳,然后我在其中进行比较和收集

我的方法不起作用,
allOrder
似乎没有像我预期的那样收集所有对象

var allOrder = []; // gather all orders and push them

do {
  Order.find({ date: sDate })
    .then(function(order) {
      allOrder.push(order); //pushing order
    })
    .catch(next);

  // create new search date (normally in another function)
  startDate.setDate(startDate.getDate() + 1); // increment a day
  startYear = startDate.getFullYear();
  startMonth = startDate.getMonth() + 1;
  startDay = startDate.getDate();
  if (startMonth < 10) startMonth = "0" + startMonth; // fix format

  sDate = `${startYear}-${startMonth}-${startDay}`; // create new search date
  dayStart++;
} while (dayStart < days); // check the day range

res.send(allOrder); //once all days are done, send.

正如Chris在我的评论中告诉我的那样,解决方案非常简单

Order.find ({
    date: {
        $gte : sDate,
        $lt : eDate
    }
}).then (function (order){
    res.send(order);
}).catch(next)

我的sDate是我自己的时间戳(或者我猜是你想要的任何值),对于eDate也是如此。这项工作完美而优雅

Order.find()
是异步的;此代码将调用res.send(allOrder)甚至在第一个DB操作完成之前。我还将冒险猜测mongodb支持在时间戳之间抓取记录。编写这样的日期不仅不可读,难以调试,而且根本没有必要。这解释了为什么我的前端表现得很滑稽。我不知道该怎么办。我会让我的前端不断接收数据并将其添加到状态,直到我收到“数据结束”标志吗?不,如果必须进行多个查询,则应该使用
Promise.all()
。然而,这里有一个:@ChrisG我不知道这些参数是选项。成功了。
Order.find ({
    date: {
        $gte : sDate,
        $lt : eDate
    }
}).then (function (order){
    res.send(order);
}).catch(next)