我正在做一个流星应用程序,我有每周格式时间表的数据-
events:
event:
day: "Monday"
time: "9am"
location: "A"
event:
day: "Monday"
time: "10am"
location: "B"每天都有许多条目。我能不能运行一个查询来返回一个格式的对象-
day: "Monday"
events:
event:
time: "9am"
location: "A"
event:
time: "10am"
location: "B"我可以将对象存储在第二种格式中,但为了便于删除和更新单个事件,我更喜欢使用第一种格式。
如果有很好的方法,我也想把每周一天的订单退回去。
发布于 2015-07-20 16:37:43
若干备选方案:
Collection.find()查询,并使用cursor.Observe()和条件修改的巧妙组合扩展/减少/修改它。看看这个答案,它对我来说很管用(我需要一个带有黑名单的字段的和,但是您可以很容易地将它调整到您的组/排序案例中):https://stackoverflow.com/a/30813050/3793161。如果您需要更多关于这方面的详细信息,请评论insert上更新它们。编辑在这里对您的评论有一些想法:
如果您坚持您在问题中描述的内容,您将需要七个文档,每天一个文档,其中包含一个events字段,您可以在其中放置所有事件。我的第二个解决方案是很好的,如果您需要在发送之前重新工作一个集合结构。但是,在您的示例中,您只需要一个对象week,其中有7个子对象与一周中的时间相匹配。
我建议你采取可能的办法:
$group文档所述,您将无法直接获得排序数组。$group不订购它的输出文档。
因此,您需要在返回方法结果之前使用_.sortBy()对它们进行排序(按日排序和每天按小时排序)。顺便说一句,如果您想知道方法调用( clientside )中发生了什么,那么应该如何编写这个调用:
Meteor.call("getGroupedDailyEvents", userId, function(error, result){
if(error){
console.log("error", error);
}
if(result){
//do whatever you need
}
});它假设time字段的格式是这样排序的。如果没有,您只需要创建一个函数来对其格式进行相应的排序,或者将原始格式更改为更适合的格式。
其余的(HTML)只是在周一事件上使用{{#each monday_events}}迭代
发布于 2015-07-20 16:36:48
要实现所需的结果,请使用聚合框架,其中$group管道操作符对所有输入文档进行分组,并将累加器表达式$push应用到组中以获取事件数组。
你的管道应该是这样的:
var Events = new Mongo.Collection('events');
var pipeline = [
{
"$group": {
"_id": "$day",
"events": {
"$push": {
"time": "$time"
"location": "$location"
}
}
}
},
{
"$project": {
"_id": 0, "day": "$_id", "events": 1
}
}
];
var result = Events.aggregate(pipeline);
console.log(result)您可以添加陨石:总包来实现Meteor中的聚合:
添加到您的应用程序
meteor add meteorhacks:aggregate因为这个包在.aggregate实例上公开了Mongo.Collection方法,所以您可以定义一个获取聚合结果数组的方法。例如
if (Meteor.isServer) {
var Events = new Mongo.Collection('events');
Meteor.methods({
getGroupedDailyEvents: function () {
var pipeline = [
{
"$group": {
"_id": "$day",
"events": {
"$push": {
"time": "$time"
"location": "$location"
}
}
}
},
{
"$project": {
"_id": 0, "day": "$_id", "events": 1
}
}
];
var result = Events.aggregate(pipeline);
return result;
}
});
}
if (Meteor.isClient) {
Meteor.call('getGroupedDailyEvents', logResult);
function logResult(err, res) {
console.log("Result: ", res)
}
}https://stackoverflow.com/questions/31521229
复制相似问题