1

我从以下位置复制代码:Meteor 文档中的消息计数示例如何工作?这没用。客户端调用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)
    }); 
}
4

2 回答 2

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!)
    }
 })
});
于 2012-09-14T06:55:18.530 回答
0

像这样试试

Counts = new Meteor.Collection("counts-by-room"); /* correct name of the collection */
/*... subscribing stuff */
Counts.findOne('counts') /* this is the count you published */
于 2012-09-12T02:43:45.270 回答