1

以下からコードをコピーします: Meteor ドキュメントのメッセージ数の例はどのように機能しますか? それは動作しません。client callCounts.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 に答える