流星,一对多的关系 &仅将字段添加到发布中的客户端集合? [英] Meteor, One to Many Relationship & add field only to client side collection in Publish?
问题描述
任何人都可以看到这段代码中可能有什么问题,基本上我想检查当前登录用户是否已共享帖子并向客户端集合添加一个临时字段:isCurrentUserShared.
Can anyone see what may be wrong in this code, basically I want to check if a post has been shared by the current logged in user AND add a temporary field to the client side collection: isCurrentUserShared.
这在加载新页面并从现有共享中填充时第一次起作用,或者在页面加载后仅在第一次向共享集合中添加或删除记录时.
This works the 1st time when loading a new page and populating from existing Shares, or when adding OR removing a record to the Shares collection ONLY the very 1st time once the page is loaded.
1) isSharedByMe 仅更改状态 1 次,然后仍会根据 console.log 调用回调,但在我第一次添加或删除记录后,不会在 Posts 集合中更新 isSharedByMe.第一次就成功了.
1) isSharedByMe only changes state 1 time, then the callbacks still get called as per console.log, but isSharedByMe doesn't get updated in Posts collection after the 1st time I add or remove a record. It works the 1st time.
2) 为什么回调会被连续调用两次,即向 Sharescollection 添加 1 条记录会触发 2 次调用,如 console.log 所示.
2) Why do the callbacks get called twice in a row, i.e. adding 1 record to Sharescollection triggers 2 calls, as show by 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();
});
推荐答案
就我个人而言,我会采用一种非常不同的方式,通过使用 $in 运算符,并在记录中保留一组 postId 或 shareId.
Personally, I'd go about this a very different way, by using the $in operator, and keeping an array of postIds or shareIds in the records.
http://docs.mongodb.org/manual/reference/operator/查询/输入/
我发现发布函数在保持简单时效果最好,如下所示.
I find publish functions work the best when they're kept simple, like the following.
Meteor.publish('posts', function() {
return Posts.find();
});
Meteor.publish('sharedPosts', function(postId) {
var postRecord = Posts.findOne({_id: postId});
return Shares.find{{_id: $in: postRecord.shares_array });
});
这篇关于流星,一对多的关系 &仅将字段添加到发布中的客户端集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!