Search code examples
meteoriron-router

What is wrong with my routing


I'm trying to change my route http://localhost:3000/posts/id to http://localhost:3000/posts/title but when changing params in router.js from '_id' to 'title' i'm getting empty page.

I have a form that working fine:

Template.addpost.events({
    'submit form': function(e) {
        e.preventDefault();
        var query = {
            title: $(e.target).find('[name=title]').val(),
            text: $(e.target).find('[name=text]').val() ,
            image: $(e.target).find('[name=image]').val(),
            intro: $(e.target).find('[name=intro]').val(),
            friendlyTitle: slugify($(e.target).find('[name=title]').val()),
            author: Meteor.user().profile.name
        };
        query._id = Posts.insert(query);
        Router.go('index');
    }
  });

And my router.js:

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  waitOn: function() { return Meteor.subscribe('posts'); }

});

    Router.map(function() {
      this.route('index', {path: '/'});
      this.route('addpost', {path: '/add'});
      this.route('postPage', {
            path: '/posts/:friendlyTitle', //empty page with friendlyTitle, but with _id working good
            data: function() { console.log(this.params.friendlyTitle);return Posts.findOne(this.params.friendlyTitle); //same, with _id working good}

        });
    });
    Router.onBeforeAction('loading');

postPage.html:

<template name="postPage">
    <div class="container main">
        <div class="col-md-12"><h1>{{title}}</h1></div>
        <div class="col-md-12">
            {{{text}}}
        </div>
    </div>
</template>

Solution

  • You need to specify the query criteria.

    You have this.

    return Posts.findOne(this.params.friendlyTitle);
    

    change to this.

    return Posts.findOne({title:this.params.friendlyTitle});
    

    if not the find will take this.params.friendlyTitle like an _id and will return and empty query

    Routes more clean*

    Change the route to this.

    Router.route('/posts/title', {
      name: 'postPage',
      waitOn:function(){
       return Meteor.subscribe('posts'); //or use the new subscritionReady
      },
      data: function() { 
        console.log(this.params.title)
        console.log(Posts.findOne({title:this.params.title});)
        return Posts.findOne({title:this.params.title}); 
      }
    });
    

    Using Router.map

    Router.map(function () {
      this.route('postPage', {
        path: '/posts/:title',
        waitOn:function(){
         return Meteor.subscribe('posts'); //or use the new subscritionReady
        },
        data: function(){
          return Posts.findOne({title:this.params.title});
        }
      });
    }); 
    

    Use différentes Router.map or Router.route for each route.