MeteorJS + Iron-Router: How can I call the next item in the collection using pathFor?

我的未来我决定 提交于 2019-12-03 09:07:22

I created sample application which exactly do what you need. Please check it : https://github.com/parhelium/meteor-so-post-next-prev/tree/master

Briefly explanation of important parts of this code ( see repo to find more details ):

Server Side

First you need to have some model:

 {title:"1 post", createdAt:moment("01-10-1995", "DD-MM-YYYY").toDate()}

and publish functions:

Meteor.publish("postDetailsNext",function(postId){ });
Meteor.publish("postDetailsPrev",function(postId){ });
Meteor.publish("postDetails",function(postId){});

The 'tricky' part is how to write queries for taking next and prev posts.

Meteor.publish("postDetailsNext",function(postId){

      // load post object which should be displayed in 'postDetails' route
      var post = Posts.findOne({_id:postId});

      // find one post from sorted cursor which is older than main post 
      return Posts.find({createdAt:{$gt:post.createdAt}},{sort:{createdAt:1}, limit:1})
});

and similar :

Meteor.publish("postDetailsPrev",function(postId){  
      var post = Posts.findOne({_id:postId});
      return  Posts.find({createdAt:{$lt:post.createdAt}},{sort:{createdAt:-1}, limit:1})
  });

Note that queries from above publish functions differs in sort field.

Client Side

this.route('postDetails',{
      where:'client',
      path:'/post/:_postId',
      template:'postDetails',
      waitOn:function(){
        return [
            Meteor.subscribe('postDetails', this.params._postId),
            Meteor.subscribe('postDetailsPrev', this.params._postId),
            Meteor.subscribe('postDetailsNext', this.params._postId)
        ]
      },
      data:function(){
        var post = Posts.findOne({_id:this.params._postId});
        if(post == null) return {};
        else
            return {
                post : Posts.findOne({_id:post._id}, {limit:1}),
                prev : Posts.findOne({createdAt:{$lt:post.createdAt}},{sort:{createdAt:-1}}),
                next : Posts.findOne({createdAt:{$gt:post.createdAt}},{sort:{createdAt:1}})
            }
        }
      }
    })
Mabed

You can do this without using iron router pathFor

by using this package https://github.com/alethes/meteor-pages it give a varies options to use a paginations

Also you may be interest to check this URL's Best pattern for pagination for Meteor http://www.youtube.com/watch?v=WSwe_weshQw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!