Merging collections in Meteor

前端 未结 3 1826
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 15:20

Imagine you have multiple collections you want displayed on a single social news feed, for example Posts and Users (new signups). How would you rea

3条回答
  •  执念已碎
    2020-12-10 15:53

    Idea 1 seems to work out of the box. I created a new meteor project and change it as follows:

    test.js:

    Users = new Meteor.Collection("users");
    Posts = new Meteor.Collection("posts");
    
    if (Meteor.isClient) {    
      Template.hello.array = function () {
          var a = Users.find().fetch()
              .concat(Posts.find().fetch());
          return _.sortBy(a, function(entry) { return entry.votes; });      
      };
    }
    
    if (Meteor.isServer) {
      Meteor.startup(function () {
          // code to run on server at startup
          Users.insert({name: "user1", votes: 1});
          Users.insert({name: "user2", votes: 4});
          Users.insert({name: "user3", votes: 8});
          Users.insert({name: "user4", votes: 16});
    
          Posts.insert({name: "post1", votes: 2});
          Posts.insert({name: "post2", votes: 4});
          Posts.insert({name: "post3", votes: 6});
          Posts.insert({name: "post4", votes: 8});
    
      });
    }
    

    test.html:

    
      test
    
    
    
      {{> hello}}
    
    
    
    

    This gives the expected list:

    1 user1
    2 post1
    4 user2
    4 post2
    6 post3
    8 user3
    8 post4
    16 user4
    

    Then I did Users.insert({name: "new", votes: 5} in the console and got (reactively):

    1 user1
    2 post1
    4 user2
    4 post2
    5 new
    6 post3
    8 user3
    8 post4
    16 user4
    

提交回复
热议问题