gpt4 book ai didi

javascript - Meteor mongodb 数据透视和更优雅的代码

转载 作者:行者123 更新时间:2023-11-28 01:20:34 25 4
gpt4 key购买 nike

我这里有一个包含所有相关详细信息的垃圾箱:http://jsbin.com/ribor/1/edit?js,output

但是为了方便回答,这里有详细信息。我有这些模型示例:

Orders = {
_id: "T487wBz7Pvzjo2QHh",
beverages: [
{
_id: "8ea26bb103efae385f80f881",
delivered: false,
name: "Wine",
units: "55"
}
],
location: "yTKWLFwSDvp3DyCkx",
locationName: "Ladies Garden",
locationNumber: "101",
timestamp: 1398393004864,
user_id: "W3Fdq36Ts2TdWxCRP",
username: "jgeezy"
};

Locations = {
_id: "yTKWLFwSDvp3DyCkx",
beverages: [
{
_id: "e5552a68266ed76895b8228a",
fillTo: "10",
name: "Wine Coolers",
orderWhen: "10",
startUnits: "10"
}
],
name: "Teen Cabana",
number: "103",
organization: "Super Happy Teens!",
vendor: false
};

我需要在每个位置的表中呈现一些行,以显示每个位置未交付饮料订单的总数。我已经写好了这个函数:

Template.dashboardOrders.undeliveredOrders = ->
undeliveredOrders = Orders.find({'beverages.delivered': false}, {
transform: (order) ->
order.unfilledOrders = 0
_.each order.beverages, (bev) ->
if not bev.delivered
order.unfilledOrders += 1
order
})

但这给了我一个按顺序和时间戳排序的数组。我正在寻找的输出是一个按唯一位置和时间戳排序的数组。不完全确定如何到达那里,但我一直在尝试不同的映射和减少方法,因为我觉得这是要走的路,但我被困住了。非常感谢任何帮助!

奖励 另外,我的方法感觉不太优雅,因为必须返回订单对象并使用 += 来递增。我感觉可能有更好的方法来做到这一点。

最佳答案

我只是要添加第二个答案来回答 @jasongonzales 的第二个问题。我的第一个答案,只是查询,返回所有未交付的订单,并按位置和时间戳对它们进行排序。根据评论,还需要以下内容:

I want to include all the orders that are undelivered per location and I need a count of the undelivered orders per location.

有很多方法可以实现这一目标。我认为最简单的方法是不要尝试将所有内容都挤入查询中,而是处理查询返回的数据:

Template.dashboardOrders.undeliveredOrdersByLocation = ->
orders = Orders.find
beverages.delivered: no
,
sort:
location: 1
timestamp: 1

# Create an object, locations, to hold the undelivered orders by location;
# the object keys are the location _id's, and the values are the mongo docs:
locations = {}

# Loop through all the undelivered orders and add each to the locations object:
orders.forEach (doc) ->
unless locations[doc.location]?
locations[doc.location] =
undeliveredOrders: []
undeliveredOrdersCount: 0
location: doc.location
locationName: doc.locationName
locationNumber: doc.locationNumber
# etc., whatever else your template needs

locations[doc.location].undeliveredOrders.push doc
locations[doc.location].undeliveredOrdersCount++

# Convert the locations object into an array for use in your template:
return _.values(locations) # Don't need to preserve the keys

您没有提供模板的示例,但您可以像这样使用 locations 数组:

{{#each undeliveredOrdersByLocation}}
There are {{undeliveredOrdersCount}} undelivered orders for {{locationName}}:
{{#each undeliveredOrders}}
An order submitted by {{username}} on {{timestamp}} for:
<ul>
{{#each beverages}}
<li>{{units}} units of {{name}} need to be delivered.</li>
{{/each}}
</ul>
{{/each}}
{{/each}}

关于javascript - Meteor mongodb 数据透视和更优雅的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com