Meteor: publish 2 different projections of array elements

前端 未结 1 535
清歌不尽
清歌不尽 2021-01-07 15:34

I have elements like this one in a collection:

{
    array: [{ a:10, b: {...} }, { a:30, b: {...} }, { a:50 b: {...} }]
}

In one publicatio

相关标签:
1条回答
  • 2021-01-07 15:42

    I examined different approaches. The problem can be solved on a case-by-case basis by carefully picking fields and minding subscription order, but these solutions are flimsy and rely on non-documented arbitrary conditions.

    The only real, generic solution is a virtual collection. The simplest case is simply publishing a cursor under a different, client-side collection name. For example:

    function publishVirtual(sub, name, cursor) {
      var observer = cursor.observeChanges({
        added  : function(id, fields) { sub.added(name, id, fields) },
        changed: function(id, fields) { sub.changed(name, id, fields) },
        removed: function(id)         { sub.remove(name, id) }
      })
    
      sub.onStop(function() {
        observer.stop() // important. Otherwise, it keeps running forever
      })
    }
    

    And then, in your publication, instead of returning a cursor:

    var cursor = Users.find()
    publishVirtual(this, 'virtualUsers', cursor)
    this.ready()
    
    0 讨论(0)
提交回复
热议问题