簡體   English   中英

如何從 Meteor.js 中的數組中獲取數組

[英]How to get an array from an array in Meteor.js

每個人。 當在下拉列表中選擇該科目時,我希望在表格中顯示注冊該科目的學生。 這些學生的 ID 存儲在一個數組中。 問題是從文檔中檢索到的這個 ID 數組看起來有點奇怪。 好像數組中有一個數組。 像這樣在控制台中顯示在控制台中顯示

 {enrollment: Array(2)}
     enrollment: Array(2)
     0: "b1602231"   
     1: "B1560124"   
     length: 2 
     __proto__: Array(0)
     __proto__: Object

它拋出了一個錯誤:模板助手中的異常:錯誤:$in需要一個數組

那我怎么能解決這個問題呢? 如果有人能給我一些想法,我將不勝感激。

下面是事件處理程序和幫助程序。

Template.subject.events({
  ‘change #dropdown’: function(event, template) {
    var selectedValue = $(event.target).val();
    var array = subject.findOne( { subjectCode:selectedValue }, { fields:{ _id:0, enrollment:1 } } );
    Session.set(‘studentEnrolled’,array);
  }
});

Template.student.helpers({
  student: function() {
    var listOfStudent = Session.get( ‘studentEnrolled’ );
    return student.find( { studentID: { $in:listOfStudent } } );
  }
});

//HTML

<template name="student">
        {{#each student}}
        <tr>
          <td>{{name}}</td>
        </tr>
        {{/each}}
</template>

從數據中查找獲取one records 您可以使用[data]在數組中進行轉換

var array = subject.findOne({subjectCode:selectedValue}, {fields:{_id:0, enrollment:1}});
Session.set(‘studentEnrolled’,[array]);
}

// 異步更新更多: https : //blog.meteor.com/using-promises-and-async-await-in-meteor-8f6f4a04f998

Template.hello.onCreated(function helloOnCreated() {
  this.list = new ReactiveVar([]);
  Meteor.call('getHobbits', (error, result) => {
    this.list.set(result);
  });
});

Template.hello.helpers({
  hobbits() {
    return Template.instance().list.get();
  },
});

從論壇復制我的答案:

首先,您在此處獲取整個主題文檔(在第一個答案之后,將該數組包裝到另一個數組中):

Session.set('studentEnrolled',[array]);

這意味着當您在這里搜索時:

return student.find({studentID:{$in:listOfStudent}});

您正在傳遞一個包含文檔的數組,而不是注冊數組。

您要做的是將注冊存儲在會話中:

Session.set('studentEnrolled', array.enrollments);

我還建議重命名變量array因為它不是數組,這可能會導致您感到困惑

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM