繁体   English   中英

复杂的collection.find()查询并使用{{#each collection}}进行渲染

[英]Complex collection.find() query and render it using {{#each collection}}

我在MongoDB中使用以下初始数据收集了“成员”:

        Members.insert({
            event: 1,
            username: "Juan Machado",
            answers: ["Tennis", "Golf", “Bowling”]
        });

        Members.insert({
            event: 1,
            username: "Elvis Crespo",
            answers: [“FootBall”, “Tennis”, “Squash”]
        });

        Members.insert({
            event: 1,
            username: "Roman Santos",
            answers: [“Golf”, “Bowling”]
        });

如果登录的用户是第一个插入的用户(“ Juan Machado”),我想向他显示在同一运动中匹配的其他成员的用户名,在渲染的模板中显示如下内容:


“ Juan Machado”这是您的比赛:

  • “ Roman Santos”与您进行的比赛:1.高尔夫| 2.保龄球
  • “ Elvis Crespo”与您进行的比赛:1.网球

有任何帮助如何使用{{#Each Members}}在Meteor中{{#Each Members}}吗? 我很难进行collection.find({})查询,也很难在模板中呈现它。

首先,通过用户名而不是用户名将用户保存在成员集合中,因为用户名会更改,而用户名不会更改。 接下来,我建议进行一系列运动。 然后,通过使用此查询,您可以检查元素是否在数组中: {"answers": {$in: [element]}} 首先使用this._id在助手中找到当前用户。 然后按他的is(或您现在的用户名)从文档中提取文档。 然后获取他的答案数组,并使用foreach循环遍历它们。 剩下的就是让您决定如何做。

注释当您在HTML中执行每个操作时,请对成员集合进行操作,并在此范围内称为帮助程序。

首先,让我们处理查找匹配的成员。 您将要使用以下命令从服务器发布此文件:

Meteor.publish('matchingMembers',function(){
  let username = Meteor.users.find({ _id: this.userId }).username;
  if ( username ){
    let myAnswers = Members.find({ username: username }).answers;
    if ( myAnswers ){
      return Members.find({ answers: { $in: myAnswers }});
    }
  }
});

在模板中,假设您已订阅发布并且已准备就绪,则需要:

{{#each otherMembers}}
  {{username}} matches with you in:
  {{#each matchingAnswers}}
    {{this}}
  {{/each}}
{{/each}}

您将需要以下帮手:

Template.myTemplate.helpers({
  otherMembers: function(){
    let myUsername = Meteor.user().username;
    return Members.find({ username: { $ne: myUsername }});
  },
  matchingAnswers: function(){
    let myAnswers = Members.findOne({ username: Meteor.user().username }).answers;
    // return the intersection of the other member's answers with the current user
    return _.intersection(this.answers,myAnswers); /
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM