我想制作一个包含几个附加字段的出版物,但我不想使用Collection.aggregate
当集合发生变化时,我的出版物更新就会丢失(所以我不能只使用self.added
在其中)。
我打算使用Cursor.observeChanges
为了实现这一目标。我有两个主要限制:
- 我不想发布所有文档字段
- 我想使用一些未发布的字段来创建新的字段。例如,我有一个字段
item
我存储数组的地方item
_ID。我不想发布它,但我想发布一个item_count
字段与我的字段数组的长度
方法如下:
我计划链接查找查询。我从来没有这样做过,所以我想知道是否可能。一般(简化)查询结构如下:http://jsfiddle.net/Billybobbonnet/1cgrqouj/(我无法在这里正确显示代码)
基于Meteor 文档中的计数示例,我将查询存储在变量中handle
为了在客户端取消订阅时停止更改通知:
self.onStop(function () {
handle.stop();
});
- 我添加一个标志
initializing = true;
在我的查询之前,我将其设置为true
就在打电话之前self.ready();
。我用这个标志来改变我的itemCount
仅当发布时变量才被初始化。所以基本上,我改变了我的switch
像那样:
switch (field) {
case "item"
if (!initializing)
itemCount = raw_document.item.length;
break;
default:
}
在对我的代码进行重大更改之前,我想检查这种方法是否良好且可行。有人可以确认我这是否是正确的方法吗?
即使字段是数据库查询的一部分,保持字段私有也相对容易。最后一个参数self.added
是传递给客户端的对象,因此您可以删除/修改/删除发送给客户端的字段。
这是你的小提琴的修改版本。这应该可以满足您的要求。 (说实话,我不确定为什么你在observeChanges
在你的小提琴中起作用,所以也许我误解了你,但是看看你问题的其余部分,这应该是这样。抱歉,如果我弄错了。)
var self = this;
// Modify the document we are sending to the client.
function filter(doc) {
var length = doc.item.length;
// White list the fields you want to publish.
var docToPublish = _.pick(doc, [
'someOtherField'
]);
// Add your custom fields.
docToPublish.itemLength = length;
return docToPublish;
}
var handle = myCollection.find({}, {fields: {item:1, someOtherField:1}})
// Use observe since it gives us the the old and new document when something is changing.
// If this becomes a performance issue then consider using observeChanges,
// but its usually a lot simpler to use observe in cases like this.
.observe({
added: function(doc) {
self.added("myCollection", doc._id, filter(doc));
},
changed: function(newDocument, oldDocument)
// When the item count is changing, send update to client.
if (newDocument.item.length !== oldDocument.item.length)
self.changed("myCollection", newDocument._id, filter(newDocument));
},
removed: function(doc) {
self.removed("myCollection", doc._id);
});
self.ready();
self.onStop(function () {
handle.stop();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)