【问题标题】:Transform data before rendering it to template in meteor在将数据渲染为流星中的模板之前转换数据
【发布时间】:2015-05-12 11:40:04
【问题描述】:

我想返回一个将字段连接在一起的文档。也就是像下面这样的结果

{
  _id: "someid",
  name: "Odin",
  profile: {
    game: {
      _id: "gameid",
      name: "World of Warcraft"
    }
  }
}

我有一个相当简单的路由控制器。

UserController = RouteController.extend({
  waitOn: function () {
    return Meteor.subscribe('users');
  },

  showAllUsers: function () {
    this.render('userList', {
      data: Meteor.users.find()
    })
  }
});

我尝试过像这样更改我的数据:

this.render('userList', { 
  data: Meteor.users.find().map(function (doc) {
    doc.profile.game = Games.findOne();
    return doc;
  })
});

但是,这并没有为用户添加“游戏”的预期效果。 (是的,Games.findOne() 有结果)

如何在流星和铁:路由器中转换光标的结果?

【问题讨论】:

  • 你不能在映射结果之前fetch() 吗?
  • 我认为如果你这样做,它不会实时更新(流星特定的东西)。如果我没记错的话,它需要返回一个游标。查了游标的__proto__,好像没有任何transform类型的函数
  • 是的,我认为它仍会实时更新,但渲染效果不佳(整个集合在模板上重新加载)
  • 啊实际上,问题看起来有点不同...我正在使用 easy search,它不允许转换文档。

标签: javascript mongodb meteor


【解决方案1】:

尝试将您的 data 定义为一个函数,以便在需要时可以动态地重新执行它。

UserController = RouteController.extend({
  waitOn: function () {
    return Meteor.subscribe('users');
  },
  showAllUsers: function () {
    this.render('userList', {
      data: function(){
        return Meteor.users.find().map(function (doc) {
          doc.profile.game = Games.findOne();
          return doc;
        });
      }
    });
  }
});

【讨论】:

    【解决方案2】:

    考虑到您使用的是简单搜索,可能更简单的方法是为profile 定义一个模板助手

    Template.userList.helpers({
      profile: function(){
        var game = Games.findOne({_id: this.gameId});
        return { game: { _id: game._id, name: game.name }};
      }
    });
    

    这假设每个用户玩一个游戏。如果你有多个,那么你可以迭代游戏的光标。

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 2019-05-28
      • 2018-02-08
      • 2016-04-30
      • 2020-01-05
      • 1970-01-01
      • 2013-12-24
      • 2015-06-29
      相关资源
      最近更新 更多