In Meteor, how can I query only the records of a given subscription?

前端 未结 3 1636
北海茫月
北海茫月 2020-12-18 07:09

I understand that a a subscription is a way to flow records into a client-side collection, from this post, and others...

However, per this post, You can have multipl

3条回答
  •  有刺的猬
    2020-12-18 07:46

    What you seem to want to do is maintain two separate collections of records, where each collection is populated by a different publication. If you read the DDP specification, you'll see that the server tells the client which collection (not publication) each record belongs to, and multiple publications can actually provide different fields to the same record.

    However, Meteor actually lets you send records to any arbitrary collection name, and the client will see if it has that collection. For example:

    if (Meteor.isServer) {
      Posts = new Mongo.Collection('posts');
    }
    
    if (Meteor.isClient) {
      MyPosts = new MongoCollection('my-posts');
      OtherPosts = new MongoCollection('other-posts');
    }
    
    if (Meteor.isServer) {
      Meteor.publish('my-posts', function() {
        if (!this.userId) throw new Meteor.Error();
    
        Mongo.Collection._publishCursor(Posts.find({
          userId: this.UserId
        }), this, 'my-posts');
    
        this.ready();
      });
    
      Meteor.publish('other-posts', function() {
        Mongo.Collection._publishCursor(Posts.find({
          userId: {
            $ne: this.userId
          }
        }), this, 'other-posts');
    
        this.ready();
      });
    }
    
    if (Meteor.isClient) {
      Meteor.subscribe('my-posts', function() {
        console.log(MyPosts.find().count());
      });
    
      Meteor.subscribe('other-posts', function() {
        console.log(OtherPosts.find().count());
      });
    }
    

提交回复
热议问题