简体   繁体   English

流星-从方法返回集合对象

[英]Meteor - Return Collection Object from Method

I'm trying to return a collection object from a Meteor method based on a set session. 我正在尝试根据设置的会话从Meteor方法返回集合对象。

Here's the method call: 这是方法调用:

Template.batches.search = function () {
    if (typeof Session.get('search-parameters') != 'undefined') {

        var searchParameters = Session.get('search-parameters');

        return Meteor.call('search', searchParameters, function(error , result){
            if (error) {
                console.log(error.reason);
            } else{
                return result;
            }
        });
    }
}

Here's the method being calledL 这就是被称为L的方法

Meteor.methods({
    search: function (session) {
        return Batches.find({event: { $regex: session}});
    }
});

I've read that a method cannot return a collection object and to use fetch() instead. 我读过一种方法不能返回集合对象,而要使用fetch()。 This returns an array, however, I'm unable to iterate over the array like a colleciton object to return the results. 这将返回一个数组,但是,我无法像colleciton对象那样遍历该数组以返回结果。 Please advise. 请指教。

Template helpers need to be synchronous. 模板助手需要同步。 There are a few ways to solve this, but here's an example: 有几种方法可以解决此问题,但这是一个示例:

Template.batches.created = function() {
  // this will be cleaned up for you when the template is destroyed
  this.autorun(function() {
    var search = Session.get('search-parameters');
    Meteor.subscribe('batchesForSearch', search);
  });
};

Template.batches.helpers({
  search: function() {
    var search = Session.get('search-parameters');
    return Batches.find({event: {$regex: search}});
  }
});

In the batches template, create an autorun which subscribes to batchesForSearch whenever the session changes. batches模板中,创建一个自动运行,每当会话更改时,该自动运行就订阅batchesForSearch Once the documents arrive on the client, they will be made available to your template via the search helper. 文档到达客户端后,将通过search助手将其提供给您的模板。

The batchesForSearch publish function could look something like this: batchesForSearch发布功能可能类似于以下内容:

Meteor.publish('batchesForSearch', function(search) {
  check(search, String);

  if (_.isEmpty(search)) {
    // make sure we do not publish the entire collection if search is empty 
    return this.ready();
  } else {
    return Batches.find({event: {$regex: search}});
  }
});

Note that we are careful to avoid publishing the entire collection in case the search is empty. 请注意,如果搜索为空,我们要避免发布整个集合。

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

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