Meteor:反应更新,级联删除/更新。规范化与非规范化

时间:2015-10-31 08:10:44

标签: meteor meteor-helper meteor-collections

如何在现有的已加入文档中进行级联删除,更新和被动更新?比方说我加入Posts集合,Meteor.users集合userId()作为作者。我可以对Posts集合进行转换功能以获取作者的用户数据,例如username并在任何帖子上显示作者的username。问题是当用户更改他/她username时,现有帖子不会被动地更新作者username。当您删除父文档时,子文档仍然存在。我使用了流行的智能软件包,例如publish-compositecollection-helpers,但问题仍然存在。任何专家流星开发者都可以帮助我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

如果你想使用collection-hooks来解决这个问题,下面的伪代码可以帮你解决:

// run only on the server where we have access to the complete dataset
if (Meteor.isServer) {
  Meteor.users.after.update(function (userId, doc, fieldNames, modifier, options) {
    var oldUsername = this.previous.username;
    var newUsername = doc.username;
    // don't bother running this hook if username has not changed
    if (oldUsername !== newUsername) {
      Posts.update({
        // find the user and make sure you don't overselect those that have already been updated
        author: userId, 
        authorUsername: oldUsername
      }, {$set: {
        // set the new username
        authorUsername: newUsername
      }}, {
        // update all documents that match
        multi: true
      })
    }
  }, {fetchPrevious: true});
}