【问题标题】:Easiest way to get Json / Collection through Meteor Iron Router通过 Meteor Iron Router 获取 Json / Collection 的最简单方法
【发布时间】:2015-06-10 01:33:31
【问题描述】:

例如,我正在创建一组路线

/ - 应该呈现主页模板

/items - 项目页面模板

/items/weeARXpqqTFQRg275 - 应该从 MongoDB 中返回具有给定 _id 的项目

这是我正在努力实现的示例

Router.route('items/:_id', function () {
  var item = return myItems.find(:_id);
  this.render(item);
});

[更新 - 已解决] 通过在服务器端使用 Router.map 而不是 Router.route 解决了这个问题

Router.map(function () {
  this.route('post', {
    path: 'items/:_id',
    where: 'server',
    action: function(){
      var id = this.params._id;
      var json = myItems.findOne({_id: id});
      this.response.setHeader('Content-Type', 'application/json');
      this.response.end(JSON.stringify(json, null, 2));
    }
  });
});

【问题讨论】:

  • 你的问题是什么?你想达到什么目的?请详细说明。谢谢。
  • 在请求 myapplication.com/items/weeARXpqqTFQRg275 后获取 myItems.find(weeARXpqqTFQRg275) 的结果
  • 你看过this Guide section吗?

标签: javascript mongodb meteor iron-router


【解决方案1】:

您的代码有几个问题。

首先,您似乎想从 url 中获取 _id 参数,但不知道如何。它存储在this.params,所以它是this.params._id

其次,您应该发送给find 的第一个参数是一个MongoDB 查询,在您的情况下为{ _id: this.params._id }

第三,这不是您在 Iron Router 中渲染内容的方式。 render 方法中的字符串参数是你要渲染的模板的name,而不是item。

假设myItems 是一个有效的集合并且您的模板名为showItem,您的代码应该类似于:

Router.route('items/:_id', {
  name: 'showItem',
  data: function () {
    return myItems.find({ _id: this.params._id });
  }
});

【讨论】:

  • 嗯,是的,这可能是一个解决方案 - 在路由器匹配定义的路径后,它会使用从函数加载的数据呈现模板。我会将其标记为正确答案,但如果有人需要呈现纯 JSON 对象而不是网站,请查看我在顶部的帖子更新。谢谢
【解决方案2】:

试试这样的:

Router.map(function () {
    this.route('items/:myItemId', {
        data: function(){
            return myItems.findOne({_id: this.params.myItemId});
        }
    });
});

祝你好运!

【讨论】:

  • 我已经找到了解决方案(检查下面问题的edit),但是您的解决方案看起来要短得多,我也会检查一下:)
  • 这令人印象深刻,虽然相当复杂。如果有效。我只记得我也使用 router.map 我会为你编辑我的答案。
猜你喜欢
  • 2016-03-31
  • 2015-06-05
  • 2014-12-31
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 2015-06-26
  • 2016-07-24
  • 2014-05-07
相关资源
最近更新 更多