【问题标题】:Single Post subscription not working in my meteor code单一帖子订阅在我的流星代码中不起作用
【发布时间】:2016-04-24 17:28:51
【问题描述】:

我想根据传递的 ID 仅显示单个元素。我正在使用流星的订阅和发布方法,同样使用 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');
}
});

【问题讨论】:

  • 你怎么能 but when i do find({}), it gets all the data and displays it, 和 {{#with studenthistory}} ?
  • find 也对我有用,但我需要做 findOne,因为我只需要显示一条记录,这是行不通的。请在此处查看完整代码:jsfiddle.net/3s6zL5hg/1

标签: mongodb meteor meteor-blaze flow-router


【解决方案1】:

当你使用_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)});
    }
});

【讨论】:

  • 感谢沙拉特!为我工作:)
  • 奇怪...不知道为什么我从不使用它,但它仍然适用于我的项目 +1
【解决方案2】:

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

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

【讨论】:

  • 感谢 Tran 的回复。我正在使用 findOne 本身,但它不起作用。所以切换到查找,而我在这里粘贴代码。 findOne 不起作用。
  • 最好的方法是尝试逐步调试。可否尝试:打印出刊物上的id/打印出刊物/页面上的posts.find({_id: id});,打开Chrome console,输入posts.find().fetch(),看看客户端有没有数据?
  • 嗨,我试过安慰,posts.find().fetch()。它给出了空数组。尝试打印 posts.find({_id: id});它显示一个对象,选择器是“{{5694f3869e8dfbde5d74438a}}”
  • 在服务器代码中,在发布方法中我对此进行了安慰 -> console.log(attendanceRegCol.find({_id: id}).fetch());即使这给出了空数组
猜你喜欢
  • 1970-01-01
  • 2018-12-18
  • 2018-12-26
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
相关资源
最近更新 更多