【问题标题】:Modify data in Meteor.publish before sending down to client在发送到客户端之前修改 Meteor.publish 中的数据
【发布时间】:2015-08-16 05:11:47
【问题描述】:

我有以下用例:

  • 我在后端的 MongoDB 中有一个用户表,它是与前端不同的服务。我使用 DDP.connect() 连接到这个后端服务。
  • 每个用户都有一组“主题”
  • users 表中的每个主题都由 id 引用,而不是 name。有一个名为“subjects”的单独表格,按 id 保存主题。

  • 我想将用户发布到客户端,但是我希望先用主题填充发布的用户。

this blog post的启发,我尝试了以下方法:

// in the backend service on port 3030
Meteor.publish('users', function(userId) {
  var _this = this;
  Meteor.users.find({
    _id: userId
  }).forEach(function(user) {
    user.profile = populate(user.profile);
    console.log(user);
    _this.changed('users', userId, {
        _id: userId,
        profile: user.profile
    });
  });
  _this.ready();
});

// in the client
var UserService = DDP.connect('http://localhost:3030');

var UserServiceProfile = UserService.subscribe('users', Meteor.userId());
console.log(UserServiceProfile);

这会在后端产生以下错误:
Exception from sub users id akuWx5TqsrArFnQBZ Error: Could not find element with id XhQu77F5ChjcMTSPr to change

所以我尝试将_this.changed 更改为_this.added。我没有收到任何错误,但更改并未显示在客户端 minimongo 中,即使我可以看到 populate 函数通过 console.log(user) 行工作。

【问题讨论】:

    标签: meteor minimongo meteor-publications


    【解决方案1】:

    我不确定您将如何修复您的代码,但您可能不需要。看起来你想要https://atmospherejs.com/maximum/server-transform 包。

    server-transform 包添加到您的项目中,并用它替换您的代码(我假设您也已将 underscore 添加到您的项目中,并且数据库中的主题集合对应于代码中名为 Subjects 的全局变量。):

    Meteor.publishTransformed('users', function(userId) {
      return Meteor.users.find({
        _id: userId
      }).serverTransform({
        'profile.subjects': function(doc) {
          var subjects = [];
          _(doc.profile.subjects).each(function(subjectId) {
            subjects.push(Subjects.findOne(subjectId));
          });
    
          return subjects;
        }
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2022-11-04
      • 2010-09-21
      • 2013-02-08
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多