如何使用Meteor中的Iron Router为动态生成的URL分配自定义ID?

时间:2015-05-14 19:16:56

标签: javascript meteor url-routing iron-router

如何将动态生成的帖子的URL作为分配给它的属性之一?说出它的名字?因此,不是events / vbMmmw6ymrWXjtXPd,而是URL是事件/事件名称

到目前为止,这是我的路线:

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

我的架构:

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
  }
}));

2 个答案:

答案 0 :(得分:1)

您应该在架构中添加uniq slug(基于名称),如:

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

然后在你的路由器中:

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

答案 1 :(得分:0)

您可以尝试使用以下内容:

var makeSlug = function (str) {
    str = str.toLowerCase();
    str = str.replace(/[^a-z0-9]+/g, '-');
    str = str.replace(/^-|-$/g, '');
    return str;
}

Events.attachSchema(new SimpleSchema({
  slug: { //example: my-name-slug
    type: String,
    autoValue: function() {
        if (this.isInsert) {
            return makeSlug(this.field('name'));
        } else if (this.isUpsert) {
            return {$setOnInsert: makeSlug(this.field('name'))};
        } else {
            this.unset();
        }
    }
  },
 (...)
}));

小心,未经测试;)请记住,如果更新名称,slug不应该更新。这被阻止了。