【问题标题】:How to concatenate (or union) the results of find() from two mongodb collections in Meteor JS?如何连接(或联合)来自 Meteor JS 中两个 mongodb 集合的 find() 的结果?
【发布时间】:2015-07-09 02:19:18
【问题描述】:

如何从 Meteor JS 中的两个 mongodb 集合中连接(或合并或联合) find() 的结果? 我最好希望将它们作为单个游标对象加入,但获取并转换为数组是可以接受的。在以下代码中,我应该使用什么来代替 UNION?注意:我不需要删除重复的元素。一个连接就足够了。

allLocations: function(){
   location_set_1 = TableA.find({'loc':{$exists:1}},{loc:1,limit:300});
   location_set_2 = TableB.find({'loc':{$exists:1}},{loc:1,limit:300});
   combined_location_set = ??UNION??(location_set_1,location_set_2)
   return combined_location_set;
}

一个(n 不完整的)解决方案可能如下,但它会返回一个数组。相反,我需要将光标对象返回给 Meteor 中的“助手”:

a=TableA.find()
b=TableB.find()
c=_.extend({},a.fetch(),b.fetch())
// c=[].concat(a.fetch()).concat(b.fetch());
return c;

【问题讨论】:

  • 一个(n 不完整的)解决方案可能如下,但它会返回一个数组。我需要将光标对象返回给 Meteor 中的“助手”: a=LocLogger.find() b=MessagesTable.find() c=_.extend({},a.fetch(),b.fetch()) // c=[].concat(a).concat(b);返回 c;
  • 对不起,实际上有两个不同的表。我修复了帖子。
  • edit您的帖子包含您对问题的任何其他信息。避免在 cmets 中添加它,因为它们更难阅读并且更容易删除。
  • 谢谢。我更新了帖子。

标签: javascript mongodb meteor mapreduce


【解决方案1】:

类似的东西?

allLocations: function(){
   var location_set_1 = TableA.find({'loc':{$exists:1}},{loc:1,limit:300}).fetch();
   var location_set_2 = TableB.find({'loc':{$exists:1}},{loc:1,limit:300}).fetch();
   var result = [];
   for (i = location_set_1.length - 1; i >= 0; i --) {
       result.push(location_set_1[i]);
   }
   for (i = location_set_2.length - 1; i >= 0; i --) {
       result.push(location_set_2[i]);
   }
   return result;
}

【讨论】:

  • 太棒了!这暂时解决了这个问题。但是有没有办法在不实际获取数据的情况下做到这一点?
  • 使用 .fetch() 时唯一的问题是,如果将结果数组传递到其他地方,则它不会是反应性的。但是在您的情况下,没有问题,因为您在哪里调用 .fetch() 计算将在数据更改时重新运行。如果不使用 fetch,可以使用 forEach : var cursor = Collection.find(); cursor.forEach(function(el){ ... });
  • 您可以使用 underscorejs.org/#union 删除两个 for 块: return _.union(location_set_1, location_set_2) :
  • 谢谢。我应该在哪里调用/使用 Meteor 中的“forEach”?在助手里面?或在 {{spacebar}} 内?
  • 将 forEach 计算放在帮助程序中,在客户端。您可以在 {{ .. }} 中调用函数
猜你喜欢
  • 1970-01-01
  • 2018-08-24
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
相关资源
最近更新 更多