Easiest way to get Json / Collection through Meteor Iron Router

941 views Asked by At

I'm creating a set of routes, for example

/ - should render home page template

/items - should items page template

/items/weeARXpqqTFQRg275 - should return item from MongoDB with given _id

This is example of what I'm trying to achieve

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

[update - solved] solved this by using Router.map on server side instead of 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));
    }
  });
});
2

There are 2 answers

1
Thiago Duarte On BEST ANSWER

There are several problems with your code.

First, it seems you want to get the _id parameter from the url and don't know how. It's stored on this.params, so it's this.params._id.

Second, the first parameter you should send to find is a MongoDB query that in your case would be { _id: this.params._id }.

Third, that's not how you render something in Iron Router. The string parameter on the render method is the name of the template you want to render, not the item.

Assuming that myItems is a valid collection and your template is called showItem, your code should be something like:

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

Try something like this:

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

good luck!