Search code examples
javascriptmeteorurl-routingiron-router

How do I assign a custom ID to a dynamically generated URL with Iron Router in Meteor?


How do I have the URL of a dynamically generated post be one of the attributes assigned to it? Say it's name? So instead of events/vbMmmw6ymrWXjtXPd the URL is events/name-of-the-event

Here's my routing so far:

    Router.route('/events/:_id', {
      name: 'event',
      data: function() { return Events.findOne(this.params._id);}
    });

And my schema:

Events = new Mongo.Collection("events");
Events.attachSchema(new SimpleSchema({
  name: {
    type: String,
    label: "Name",
    max: 200
  },
  crew: {
    type: String,
    label: "Crew"
  },
  location: {
    type: String,
    label: "Location"
  },
  date: {
    type: Date,
    label: "Date"
  },
  description: {
    type: String,
    label: "Wha'appening?",
    max: 1000
  }
}));

Solution

  • You should add uniq slug in your schema (based on name) like:

    Events.attachSchema(new SimpleSchema({
      slug: { //example: my-name-slug
        type: String
      },
     (...)
    }));
    

    And then in your Router:

    Router.route('/events/:slug', {
      name: 'event',
      data: function() { return Events.findOne({slug: this.params.slug});}
    });