MeteorJS: Routing with Backbone.js


I'm trying to implement a router with BackboneJS in my MeteorJS app. When you call the url 'localhost:3000/1' my router stores the id '1' in the session. After that I want to take the id from the session and use it in my query to select an object from my collection. But whenever I try to use a session attribute in my query it fails. So I want to know if there is a better way for routing with MeteorJS and why my query fails.



Test = new Meteor.Collection("test");

Session.set("id", null);

Template.hello.test = function () {
  var avg = 0, total = 0, cursor = Test.find(), count = cursor.count();
    total += e.number;
  avg = total / count;

  var session_id = Session.get("id");

  var test = Test.findOne({id: session_id}); //doesn't work
  if (test) {
    test.avg = avg;

  return test;

var TestRouter = Backbone.Router.extend({
  routes: {
    ":get_id":    "get_id" 
  get_id: function (get_id) {
    Session.set("id", get_id);

Router = new TestRouter;

Meteor.startup(function () {
  Backbone.history.start({pushState: true});



  {{> hello}}

<template name="hello">
  <h1>Hello World!</h1>
  {{#if test}}
    {{#with test}}
      ID: {{id}}  Name: {{name}}  AVG: {{avg}}


Test = new Meteor.Collection("test");


if (Test.find().count() < 1) 
    Test.insert({id: 1,
                 name: "test1",
                 number: 13});

    Test.insert({id: 2,
                 name: "test2",
                 number: 75});

Meteor.publish('test', function () {
  return Test.find();
6/21/2017 2:40:18 PM

Accepted Answer

I debug the code and find out that 'id' in collection is an integer, while session_id is a string. You need parseInt to convert session_id.

I use page.js for routing, which is "Micro client-side router inspired by the Express router", an excellent work from "TJ Holowaychuk".

I strongly suggest it, since Meteor and backbone have some feature collisions in Model/Collection & View/Template.

7/13/2012 10:56:02 AM

You might find iron router of interest - it's meteor specific and "knows about your subscriptions, data sources and helps you take care of common problems":

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow