Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

node.js - Meteor Subscribe doesn't update sort order of collection

// Snippet from Template
<div class="post-container">
  {{#each elements}}
    {{> post-element this}}
  {{/each}}
</div>

// Snippet from Client 
Meteor.subscribe('thePosts');

// Snippet from Server
Meteor.publish('thePosts', function(){
  return Posts.find({},  {sort:{createdAt:-1}, reactive:true});
});

When I do...

Posts.insert({body:postBody, createdAt: new Date()});

The post document gets added and appears at the end of my list, as opposed to descending order as specified in my publish function. Any idea about what I am doing wrong?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The publish function determines which records should be synced to the mini-mongo database of any subscribing clients. So sorting the data in the publish function actually has no effect on the client, as the client-side database will likely store them in some other way.

Of course you may want to use sort in a publisher's find in order to limit the number of records to the N most recent - but again this is just a way of deciding which records get synced and not how they are to be stored/used by the client.

Once the records have been synced to the client, it is up to the template code to determine how the results should be displayed. For example:

Template.myTemplate.elements = function() {
  return Posts.find({}, {sort: {createdAt:-1}});
}

Also see the "sorted publish" section of my post on common mistakes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...