我正在使用express、react 和 MongoDB。我对 Express 和 REST API 完全陌生。
我正在尝试为我的前端实现销售、订单等的分析部分。这个想法是允许搜索一系列日期,其中每个对象都有一个日期戳,然后我可以在其中进行比较和收集。
我的方法不起作用,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.
这在某种意义上是有效的,它会增加一天的时间,直到我到达某个日期。 比如我查找2018-12-25,然后增加一天,找到第二天2018-12-26。除了将数据返回到前面之外,这一切都有效。在每次查找中,我确实获取了所有数据,但我似乎无法存储它然后将它们一起发送到前面。
我的对象模型
const orderScheme = new Schema({
name: { type: String },
date: { type: String },
customerName: { type: String },
customerPhone: { type: String },
orders: { type: Array }
});
最佳答案
正如克里斯在评论中帮助我告诉我的那样,解决方案非常简单。
Order.find ({
date: {
$gte : sDate,
$lt : eDate
}
}).then (function (order){
res.send(order);
}).catch(next)
my sDate 是我自己的时间戳(或者我猜测的任何您想要的值),对于 eDate 也是如此。这工作完美且优雅。
关于javascript - 循环order.find、收集并向前端发送大量数据。方法不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54205214/