【发布时间】:2013-12-19 18:09:02
【问题描述】:
任何人都可以看到这段代码中可能有什么问题,基本上我想检查一个帖子是否已被当前登录的用户共享并向客户端集合添加一个临时字段:isCurrentUserShared。
这在加载新页面并从现有共享中填充时第一次起作用,或者在页面加载后的第一次向共享集合中添加或删除记录时。
1) isSharedByMe 仅更改状态 1 次,然后仍会根据 console.log 调用回调,但在我第一次添加或删除记录后,isSharedByMe 不会在 Posts 集合中更新。它第一次工作。
2) 为什么回调会连续调用两次,即向 Sharecollection 添加 1 条记录会触发 2 次调用,如 console.log 所示。
Meteor.publish('posts', function() {
var self = this;
var mySharedHandle;
function checkSharedBy(IN_postId) {
mySharedHandle = Shares.find( { postId: IN_postId, userId: self.userId }).observeChanges({
added: function(id) {
console.log(" ...INSIDE checkSharedBy(); ADDED: IN_postId = " + IN_postId );
self.added('posts', IN_postId, { isSharedByMe: true });
},
removed: function(id) {
console.log(" ...INSIDE checkSharedBy(); REMOVED: IN_postId = " + IN_postId );
self.changed('posts', IN_postId, { isSharedByMe: false });
}
});
}
var handle = Posts.find().observeChanges({
added: function(id, fields) {
checkSharedBy(id);
self.added('posts', id, fields);
},
// This callback never gets run, even when checkSharedBy() changes field isSharedByMe.
changed: function(id, fields) {
self.changed('posts', id, fields);
},
removed: function(id) {
self.removed('posts', id);
}
});
// Stop observing cursor when client unsubscribes
self.onStop(function() {
handle.stop();
mySharedHandle.stop();
});
self.ready();
});
【问题讨论】:
-
您在 {isCurrentUserShared: 1} 之后缺少一个括号,但我认为这不是问题所在。您看到的行为是什么?
-
谢谢我修正了错字,但这不是主要问题。
-
这是另一种使用帖子集合中的共享数组来解决此问题的方法。我不确定哪个更有效,但这种方式代码更多:stackoverflow.com/questions/20689113/…
-
从阅读有关最大文档大小 16Meg 的 Mongo 文档,并重新考虑如果发生数百万份共享会发生什么,我将远离这种模式(下面的链接),除非嵌入式数组不会太大,即少于几千个项目:stackoverflow.com/questions/20689113/…
标签: javascript mongodb meteor publish-subscribe