gpt4 book ai didi

javascript - meteor ,一对多关系&仅向发布中的客户端集合添加字段?

转载 作者:行者123 更新时间:2023-11-30 12:51:53 25 4
gpt4 key购买 nike

谁能看出这段代码中可能有什么问题,基本上我想检查帖子是否已被当前登录的用户共享,并向客户端集合添加一个临时字段:isCurrentUserShared。

这在第一次加载新页面并从现有共享中填充时起作用,或者在页面加载后仅在第一次向共享集合中添加或删除记录时起作用。

1) isSharedByMe 仅更改状态 1 次,然后仍会根据 console.log 调用回调,但在我第一次添加或删除记录后,isSharedByMe 不会在 Posts 集合中更新。它第一次工作。

2) 为什么回调会连续调用两次,即向 Sharescollection 添加 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();
});

最佳答案

就我个人而言,我会采用一种非常不同的方式,即使用 $in 运算符,并在记录中保留一组 postId 或 shareId。

http://docs.mongodb.org/manual/reference/operator/query/in/

我发现发布函数在保持简单时效果最好,如下所示。

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 });
});

关于javascript - meteor ,一对多关系&仅向发布中的客户端集合添加字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20688718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com