Search code examples
mongodbmeteoriron-routerobjectid

How to show data from mongoDB with ObjectID


i have an "back end" application which write in MongoDb (in database i have _id: with ObjectId("13f6ea...002")) i use meteor app to show information. Everything was good i displays list of information with {{#each}}. But when i wanted show one element with '_Id' nothing works.

I read this issue and adapt my code to get right root, But i can't display anything on the page. I tried to write Template helpers but it didn't helped

Db record:

  {
 _id: ObjectId("13f6ea...002"),
 url: "foo",
 title: "bar",
 published: "2014-08-22 03:26:21 UTC",
 image: "foo.jpg",
 summary: "foo ",
 categories: [
   "F",
   "B"
  ],
  ...
  }

Route:

this.route('news', {
path: '/news/:_id',
template: 'news',
waitOn: function () { 
  var id = this._id; 
  Meteor.subscribe('news', id);
},
data: function() {
  var id = this.params._id;
  return News.findOne({ _id: Meteor.Collection.ObjectID(this.params._id)});
},
 action : function () {this.render();},
});

Publish

Meteor.publish('news', function(id) {
  return News.find({_id: id}); 
});

Template which redirect to unique post

<h4><a href="{{pathFor 'news' _id=this._id.toHexString}}">{{title}}</a></h4>

And template is just {{news}}

How can i fix this?


UPDATE

My solutions to fix that:

router.js

waitOn: function () {
  var id = this._id;
  Meteor.subscribe('News', id);
},
data: function() {
  return News.findOne(new Meteor.Collection.ObjectID(this.params._id));
},

and in template

<a href="news/{{_id._str}}">


Solution

  • Navigate to the appropriate url in your browser (i.e. localhost:3000/news/[_id]), open the console and enter:

    Router.current().data()
    

    That will show you the data context of the current route. Either it returns nothing, in which case there is a fundamental problem with your News.findOne query as it's returning nothing, or (more likely) it returns the required document.

    In the latter case, as far as I can see there is no news property within that document, which is why it isn't rendering anything. If you change {{news}} to {{url}} or {{summary}} I would imagine it would render the requested property.

    If by {{news}} you're trying to render the entire document, then (aside from the fact that it will render as something like [Object]) you need to make news a property of the object returned by your data function:

    return {
        news: News.findOne({ _id: Meteor.Collection.ObjectID(this.params._id)});
    };