8

大きな「メッセージ」コレクションを持つMongoDBがあります。特定の に属するすべてのメッセージgroupId。そこで、次のような出版物から始めました。

Meteor.publish("messages", function(groupId) {
  return Messages.find({
    groupId: groupId
  });
});

そして、このようなサブスクリプション:

Deps.autorun(function() {
   return Meteor.subscribe("messages", Session.get("currentGroupId"));
});

currentGroupId最初は未定義ですが、sill mongodはメッセージを見つけるためにCPUを使い果たすため、これは私を悩ませましたgroupId == null(何もないことはわかっていますが)。

さて、私は出版物を次のように書き直そうとしました:

Meteor.publish("messages", function(groupId) {
  if (groupId) {
    return Messages.find({
      groupId: groupId
    });
  } else {
    return {}; // is this the way to return an empty publication!?
  }
});

および/またはサブスクリプションを次のように書き換えます。

Deps.autorun(function() {
   if (Session.get("currentGroupId")) {
     return Meteor.subscribe("messages", Session.get("currentGroupId"));
   } else {
     // can I put a Meteor.unsubscribe("messages") here!?
   }
});

どちらも最初は役立ちます。しかし、currentGroupId(ユーザーが別のページに移動したため) 再び未定義になるとすぐに、mongod は、最後にサブスクライブしgroupIdた . では、mongod へのクエリが停止されるように、パブリケーションの購読を解除するにはどうすればよいでしょうか?

4

4 に答える 4

5

パブリケーションに条件を追加するだけです。

Meteor.publish("messages", function(groupId) {
  if (groupId) {
    return Messages.find({
      groupId: groupId
    });
});

サブスクリプションを維持します。

Deps.autorun(function() {
  return Meteor.subscribe("messages", Session.get("currentGroupId"));
});

仕事をします。

パブリケーションを明示的に停止する必要はありません。最終的に、現在実行中のクエリを終了し、さらに別のクエリを発行すると、MongoDB はクエリされなくなります (システムのどこかでキューに入れられているようです)。

于 2013-05-28T13:06:10.277 に答える