在将数据渲染到流星中的模板之前对其进行转换

时间:2015-05-12 11:40:04

标签: javascript mongodb meteor

我想返回一个连接在一起的字段的单个文档。也就是说,结果如下

{
  _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()有结果)

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

2 个答案:

答案 0 :(得分:0)

尝试将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;
        });
      }
    });
  }
});

答案 1 :(得分:0)

鉴于您使用简单搜索,可能更简单的是为profile定义模板助手

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

这假设每个用户只有一个游戏。如果您有多个游戏,那么您可以迭代游戏游标。

相关问题