【问题标题】:Use projection for meteor publish subscribe使用流星发布订阅的投影
【发布时间】:2016-01-28 08:30:02
【问题描述】:

我有一个 UI 元素框架,它只适用于特定的数据模型(需要一个带有“text”键的对象)。这与我的 mongodb 中存在的数据模型不同。 所以我的第一个想法是使用投影并将其发布给听众。

var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db; db.Element.aggregate({$project: { _id:1, text:"$description"}});

问题是这不是一个游标,而只是一个简单的 ejson 对象。我应该使用什么策略来为 UI 框架提供所需的数据并从双方进行反应/数据绑定。

【问题讨论】:

  • 作为快速解决方法,我使用 Meteor.map 和 _.extend 将附加字段添加到光标,但它并不是真正的反应
  • 有几个包可以解决这个问题,比如 reywood:publish-composite 或 peerlibrary:reactive-publish

标签: meteor meteor-publications meteor-methods


【解决方案1】:

在您的发布中,您可以使用较低级别的发布 api 来更好地控制结果,而不是返回游标。

例如,当您从出版物返回游标时,Meteor 调用 _publishCursor 函数,如下所示:

Mongo.Collection._publishCursor = function (cursor, sub, collection) {
  var observeHandle = cursor.observeChanges({
    added: function (id, fields) {
      sub.added(collection, id, fields);
    },
    changed: function (id, fields) {
      sub.changed(collection, id, fields);
    },
    removed: function (id) {
      sub.removed(collection, id);
    }
  });

  // We don't call sub.ready() here: it gets called in livedata_server, after
  // possibly calling _publishCursor on multiple returned cursors.

  // register stop callback (expects lambda w/ no args).
  sub.onStop(function () {observeHandle.stop();});

  // return the observeHandle in case it needs to be stopped early
  return observeHandle;
};

因此,您可以修改您的出版物,基本上做同样的事情,但也可以发布一个文本字段,该字段从描述字段中获取其值,如下所示:

给定以下集合:

MyCollection = new Mongo.Collection("my_collection");

您的发布功能可能如下所示:

Meteor.publish("myPub", function () {
  var sub = this;
  var observeHandle = myCollection.find().observeChanges({
    added: function (id, fields) {
      fields.text = fields.description;  // assign text value here   
      sub.added("my_collection", id, fields);
    },
    changed: function (id, fields) {
      fields.text = fields.description;  // assign text value here 
      sub.changed("my_collection", id, fields);
    },
    removed: function (id) {
      sub.removed("my_collection", id);
    }
  });

  sub.ready()

  // register stop callback (expects lambda w/ no args).
  sub.onStop(function () {observeHandle.stop();});

};

【讨论】:

    猜你喜欢
    • 2014-05-04
    • 2014-06-16
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2018-12-26
    相关资源
    最近更新 更多