2

我只想根据传递的 ID 显示单个元素。我正在使用meteor的订阅和发布方法,同样使用FlowRouter进行路由。当我尝试使用 findOne 获取数据并传递 Id 时,它不会返回任何数据,但是当我执行 find({}) 时,它会获取所有数据并显示它,不知道为什么 findOne 不起作用..

注意:我正在尝试根据 MongoDB 提供的 Object ID(_id) 获取记录。

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');
}
});
4

2 回答 2

2

当您确实使用_id findOne 时,请将其包装到New Mongo.ObjectID 然后传递它。

试试这个代码:

  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)});
    }
});
于 2016-01-19T12:16:07.773 回答
1

find将返回一个游标,它只包含一个文档。您需要遍历它才能获取数据,或者您将助手更改为findOne

Template.stdSingleView.helpers({
    studenthistory: function(){
        var id= FlowRouter.getParam('id');
        return posts.findOne({_id: id});
    }
});
于 2016-01-19T10:25:23.403 回答