Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor and Iron Router: raise 404 when id doesn't exist

I'm using Iron Router for my urls and I have this route:

this.route('regionEdit', {
  path: '/region/:_id',
  waitOn: function() {
    return Meteor.subscribe('region', this.params._id);
  },
  data: function() {
    return Regions.findOne({
      _id: this.params._id
    });
  }
});

This works fine when I use this path http://example.com/region/xgok3Etc5mfhtmD7j

Where xgok3Etc5mfhtmD7j is the _id of region. However, when I access to http://example.com/region/whatever, the page renders normally, but without data.

How can I raise a 404 error for this?

like image 760
Braulio Soncco Avatar asked May 16 '14 22:05

Braulio Soncco


2 Answers

not a 404, but you can render a not found page by doing something like this.

this.route('regionEdit', {
  path: '/region/:_id',
  waitOn: function() {
    return Meteor.subscribe('region', this.params._id);
  },
  data: function() {
    var region = Regions.findOne({
      _id: this.params._id
    });
    if(!region)
      this.render("notFound");
    else
      return region;
  }
});
like image 166
landland Avatar answered Nov 01 '22 09:11

landland


I think you can try Plugins

According to this documentation there is already a built in plugin for this issue

Router.plugin('dataNotFound', {notFoundTemplate: 'notFound'});

And it is described as

This out-of-box plugin will automatically render the template named "notFound" if the route's data is falsey

like image 21
Süha Boncukçu Avatar answered Nov 01 '22 09:11

Süha Boncukçu