簡體   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