meteormeteor-helpermeteor-collections

Meteor: Reactive update, cascaded delete/update. Normalizing vs Denormalizing


How to do cascaded delete, update and reactive update in existing joined documents? Say for example I join Posts collection with Meteor.users collection with userId() as author. I could do transform function on the Posts collection to get user data of the author, like username and display username of the author on any post. The problem is when user changes his/her username, existing posts won't update author's username reactively. And when you delete parent document child documents are still there. I used popular smart packages like publish-composite and collection-helpers but problem still exists. Any expert meteor dev can help me on this? Thank you.


Solution

  • If you want to use collection-hooks to solve this problem, the following pseudo code should get you going:

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