【问题标题】:Iterating through an array in a Meteor.js collection遍历 Meteor.js 集合中的数组
【发布时间】:2013-07-03 09:11:32
【问题描述】:

背景:使用 Meteor.js 编写一个 Web 应用程序,用户可以在其中将棋盘游戏添加到他们的个人资料中。有一个用户集合和一个游戏集合。

我有游戏列表,每个游戏旁边都有一个按钮,以便用户可以将游戏添加到他们的个人资料中。该按钮将找到每个游戏的 _id 并将其添加到 user.games 数组中。 _id 是一个很长的哈希。

在用户的仪表板上,我希望能够显示用户“订阅”的每个游戏,但我不确定如何访问 user.games 字段。

这是我的代码:

/server/publications.js

Meteor.publish('userGames', function () {
  return Meteor.users.find({_id: this.userId},
                           {fields: {'games': 1}});
});

/client/main.js

Meteor.subscribe('userGames');

/client/views/dashboard/dashboard.html

<template name="dashboard">
<div class="dashboard">
    {{#if hasGames}}
        <ul class="games-list">
            {{#each userGames}}
                {{> game}}
            {{/each}}
        </ul>
    {{else}}
        <h3>You have not added any games to your chest</h3>
    {{/if}}
</div>
</template>

/client/views/dashboard/dashboard.js

Template.dashboard.helpers({
    hasGames: function(){

    },
    userGames: function(){

    }
});

如您所见,我不确定dashboard.js 辅助函数中的哪些内容才能访问 user.games 字段。

编辑:

所以我进行了测试以查看以下答案是否有效 - 我已更新以下内容:

dashboard.html

<template name="dashboard">
    <div class="dashboard">
        {{test}}
    </div>
</template>

dashboard.js

Template.dashboard.helpers({
    test: function(){
        var user = Meteor.user();
        return Games.find({_id: { $in: user.games  }});
    }
});

控制台显示“Uncaught TypeError: Cannot read property 'games' of undefined”

【问题讨论】:

  • 请发布您的收藏架构。

标签: meteor


【解决方案1】:

查找当前登录用户的所有游戏

Games = new Meteor.Collection("userGames");

if (Meteor.isClient) {
  Meteor.subscribe('userGames');

  Template.hello.greeting = function () {
        var user = Meteor.user();

        if(user && Array.isArray(user.games)){
          return Games.find({_id: { $in: user.games }}).fetch();
        }else{
          return [];
        }

  };
}

if (Meteor.isServer) {

  Meteor.publish('userGames', function () {
    return Meteor.users.find({_id: this.userId},
                           {fields: {'games': 1}});
  });
}

【讨论】:

  • 我试过了 - 请参阅上面的代码编辑。我现在将“[object Object]”输出到 DOM 中。
  • 当然 :-) 你需要做 Games.find({_id: { $in: user.games }}).fetch() .. 它会返回数组
  • 抱歉,我实际上在控制台中收到“Uncaught TypeError: Cannot read property 'games' of unfined”错误
  • 您是否以用户身份登录您的应用?
  • 因为 Meteor.user() 是反应性的,在这种情况下,您可能会在记录过程中遇到未定义用户的问题。我更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-26
  • 2023-03-06
  • 2021-09-12
  • 2022-01-27
  • 2014-04-11
  • 1970-01-01
相关资源
最近更新 更多