Search code examples
mongodbmeteormeteor-blazeflow-router

Single Post subscription not working in my meteor code


I want to display only single elements based on the ID passed. I am using the subscribe and publish method of meteor for the same, also FlowRouter for Routing. When i try to get the data using findOne and pass the Id, it does't return any data, but when i do find({}), it gets all the data and displays it, not sure why findOne is not working..

Note : I am trying to fetch record based on the Object ID(_id) provided by MongoDB.

posts = Mongo.collection("allPosts");

<Template name="stdSingleView">
    {{#if Template.subscriptionsReady}}
    {{#with studenthistory}}
    {{id}} - {{name}}
    {{/with}}
    {{else}}
    Loading....
    {{/if}} 
</Template>

Template.stdSingleView.onCreated(function(){
var self = this;
self.autorun(function(){
var Id = FlowRouter.getParam('id');
self.subscribe('singlePost', Id);
});
});

Template.stdSingleView.helpers({
studenthistory: function(){
var id= FlowRouter.getParam('id');
return posts.findOne({_id: id});
}
});

if (Meteor.isServer) {
Meteor.publish("allposts", function() {
return posts.find({});
});

Meteor.publish('singlePost', function(id) {
check(id, String);
return posts.find({_id: id});
});
}

pages.route( '/:id', {
name: 'singleView',
action: function( params ) {
BlazeLayout.render('stdSingleView');
}
});

Solution

  • When you do findOne using _id, Please wrap it to the New Mongo.ObjectID and then pass it.

    Try this code :

      Meteor.publish('singleStudent', function(id) {
        check(id, String);
        return attendanceRegCol.find({"_id": new Mongo.ObjectID(id)});
      });
    
      Template.studentSingleView.helpers({
        studenthistory: function(){
          var id= FlowRouter.getParam('id');
          return attendanceRegCol.findOne({"_id": new Mongo.ObjectID(id)});
        }
    });