如何在Meteor中订阅发布集合?

时间:2012-09-12 01:32:09

标签: meteor publish-subscribe

我从以下代码复制代码:How does the messages-count example in Meteor docs work?它不起作用。客户端调用Counts.find().count()方法,我希望它输出1但结果是0,你能告诉我为什么吗?

//server code
if (Meteor.is_server)
{
    Meteor.startup(function (){
      console.log("server is startup...");
      Messages = new Meteor.Collection("messages");
      if(Messages.find().count() == 0){
      for(var i=0;i<7;i++){
        Messages.insert({room_id:"00"+i,text:"message "+i});
      }
    }
    console.log("room_id:001 messages count="+Messages.find({room_id:"001"}).count());
    //print--->room_id:001 messages count=1 (it's ok)

    Meteor.publish("counts-by-room", function (roomId) {
      var self = this;
      var uuid = Meteor.uuid();
      var count = 0;

      var handle = Messages.find({room_id: roomId}).observe({
        added: function (doc, idx) {
        count++;
        self.set("counts", uuid, {roomId: roomId, count: count});
        self.flush();
      },
      removed: function (doc, idx) {
      count--;
      self.set("counts", uuid, {roomId: roomId, count: count});
      self.flush();
    } 
    // don't care about moved or changed
    });
    // remove data and turn off observe when client unsubs
    self.onStop(function () {
      handle.stop();
      self.unset("counts", uuid, ["roomId", "count"]);
      self.flush();
     });
     });
     });
}

//client code
if (Meteor.is_client)
{
    Meteor.startup(function () {
      Counts = new Meteor.Collection("counts");
      Session.set("roomId","001");
      Meteor.autosubscribe(function () {
      Meteor.subscribe("counts-by-room", Session.get("roomId"));
    });
    console.log("I client,Current room "+Session.get("roomId")+" has " 
     + Counts.find().count() + " messages.");
    //print--->I client,Current room 001 has 0 messages.(trouble:I expect it to output "...has 1 messages" here)
    }); 
}

2 个答案:

答案 0 :(得分:1)

我尝试了很多次,我发现了这个错误。 将客户端代码更改为如下所示,它将打印正确的结果。

//client code
Meteor.startup(function () {
  Counts = new Meteor.Collection("counts");
  Session.set("roomId","001");
  Meteor.autosubscribe(function () {
    Meteor.subscribe("counts-by-room", Session.get("roomId"));
    data = Counts.findOne();
    if(data){
      console.log("I client,Current room "+Session.get("roomId")+" has " 
     + data.count + " messages.");
     //print--->I client,Current room 001 has 1 messages.(now it's ok!)
    }
 })
});

答案 1 :(得分:0)

尝试那样

Counts = new Meteor.Collection("counts-by-room"); /* correct name of the collection */
/*... subscribing stuff */
Counts.findOne('counts') /* this is the count you published */