Search code examples
mongodbmeteoriron-router

access data with routes


I have a courses collection

{courses{{course1_title,id,author,pages[{title,content,model, etc...},
              [ etc...]{course2,....}}

I'm trying to display the current page's data inside the courses collection through the router

this.route('page', {
    path: '/:title',
    data: function() {
    return courses.findOne({'pages.title':this.params.title};

    }

});

I would like to display the current page's data like this:

<template name="page">
<div class ="container page">
    <h1>Page</h1>
    <!--display current page data -->
    <h3>{{title}}</h3>
    <div>{{ an other content}} etc..... </div>  
</div>

For now, the router returns the entire course's data and the title displayed is the course's title. I don't find how to access the current page's data in order to display it in the page's template.

I tried

return courses.findOne({'pages.title':this.params.title}{fields:{{'pages.title':this.params.title}:1}}   

and a lot of other ways. I didn't find it.

What is the right way?


Solution

  • Your current query will search all the courses for a matching page title, then return the entire course (with all the pages)

    You should return only the data for the page in question:

    course = courses.findOne({pages: { $elemMatch: { title: this.params.title }});
    return course.pages[0]
    

    As an aside it's probably better to create a separate collection for pages (with each page linking back to the course id). Although that's less "Mongo", Meteor can only operate reactively over collections, not sub-documents.