本文介绍了Meteor:发布数组元素的 2 个不同投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个集合中有这样的元素:

I have elements like this one in a collection:

{
    array: [{ a:10, b: {...} }, { a:30, b: {...} }, { a:50 b: {...} }]
}

在一个可以返回数百个结果的出版物中,我将数组投影到只有 a 字段并且重量更轻:

In one publication, that can return hundreds of results, I project the array toonly have the a field and weigh less:

return Col.find({}, { fields: { 'array.a': 1 } })

在另一篇文章中,我发布了一个完整的文档:

In another one, I publish a single full document:

return Col.find({ _id: ObjectId(...) })

第二次发布缺少从每个数组项中排除的字段第一次发布,有时.刷新页面(可能会改变订阅顺序?)修复了错误.

The 2nd publication is missing the fields excluded from each array item inthe first publication, sometimes. Refreshing the page (perhaps changingthe order of subscriptions?) fixes the bug.

如何在我的大型出版物中发布减少的数组项,以及完整的单个出版物中的元素?

How can I publish reduced array items in my large publication, and the fullelements in the single publication?

推荐答案

我研究了不同的方法.该问题可以通过仔细选择字段和注意订阅顺序逐案解决,但这些解决方案是站不住脚的,并且依赖于未记录的任意条件.

I examined different approaches. The problem can be solved on a case-by-case basis by carefully picking fields and minding subscription order, but these solutions are flimsy and rely on non-documented arbitrary conditions.

唯一真正通用的解决方案是虚拟收藏.最简单的情况是简单地在不同的客户端集合名称下发布游标.例如:

The only real, generic solution is a virtual collection. The simplest case is simply publishing a cursor under a different, client-side collection name. For example:

function publishVirtual(sub, name, cursor) {
  var observer = cursor.observeChanges({
    added  : function(id, fields) { sub.added(name, id, fields) },
    changed: function(id, fields) { sub.changed(name, id, fields) },
    removed: function(id)         { sub.remove(name, id) }
  })

  sub.onStop(function() {
    observer.stop() // important. Otherwise, it keeps running forever
  })
}

然后,在您的出版物中,而不是返回 cursor:

And then, in your publication, instead of returning a cursor:

var cursor = Users.find()
publishVirtual(this, 'virtualUsers', cursor)
this.ready()

这篇关于Meteor:发布数组元素的 2 个不同投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 02:18
查看更多