流星:我在搜索集合并返回结果时遇到问题。调用方法时出现异常。没有定义的

时间:2016-07-04 22:14:20

标签: javascript mongodb search meteor meteor-methods

我有一个名为"类别"的项目列表的集合。每个类别都有一个_id和一个名称字段。我试图简单地返回对类别名称的搜索

这是文档结构。每个列表项都具有这些属性。我试图瞄准名字'字段,但我得到错误

enter image description here

I20160704-22:47:42.976(1)?调用方法' findCategory' ReferenceError:未定义id

客户端/ HTML

 <form class="form-inline">
  <input type="text" class="form-control" id="searchCategory" placeholder="Search for Category">
  <button type="submit" class="btn btn-info">Search</button>
</form>



 {{#if foundCategory}}
      <div class="foundCategory">
        <button type="button" class="btn btn-default" id="follow">Follow @{{foundCategory.name}}</button>
      </div>
    {{/if}}
    </template>

服务器/ JS

Meteor.methods({
  'findCategory': function(name) {
    return Meteor.CategoryCollection.findOne({
      _id: id          
}, {
      fields: { 'name': 1 }
    });
  }
});

我试过

Meteor.methods({
      'findCategory': function(name) {
        return CategoryCollection.findOne({
          name : name         
    }, {
          fields: { 'name': 1 }
        });
      }
    });

但我得到了错误。

调用方法&#39; findCategory&#39; TypeError:无法调用方法&#39; findOne&#39;未定义的

我如何归还所需的文件?

修改

我使用rest2ddp来调用json数据并将其插入到CategoryCollection

我还将Meteor.CategoryCollection改为简单的CategoryCollection

服务器/ main.js

REST2DDP.publish("CategoryPublication", {
  collectionName: "CategoryCollection",
  restUrl: "http://localhost:8888/wordpress/wp-json/wp/v2/categories",
  jsonPath: "$.*",
  pollInterval: 5000,
});

client.subscriptions.js

CategoryCollection = new Mongo.Collection("CategoryCollection");
Meteor.subscribe("CategoryPublication");
Tracker.autorun(function () {
  console.log(CategoryCollection.find().fetch());
});

2 个答案:

答案 0 :(得分:0)

你需要定义

CategoryCollection = new Mongo.Collection("CategoryCollection");

服务器端和客户端。

答案 1 :(得分:0)

您基本上是在寻找&#34; id &#34;其中&#34; id &#34;尚未定义。

尝试传递文档&#34; id &#34;如果你有它可用的方法:

Meteor.methods({
  'findCategory': function(id, name) {
    return Meteor.CategoryCollection.findOne({
      _id: id          
}, {
      fields: { 'name': name }
    });
  }
});

如果您希望在任何文档中找到字段:{&#39; name&#39;:1} ,请忽略第一个对象 {_id:id} 部分。

Meteor.methods({
      'findCategory': function(name) {
        return Meteor.CategoryCollection.findOne({
          fields: { 'name': name }
        });
      }
    });