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

前端 未结 2 1046
轮回少年
轮回少年 2021-02-11 03:56

I did a lot of research before posting this question and couldn\'t find the answer. I\'m sure it\'s a simple task, but it\'s going over my head for some reason.

I have

2条回答
  •  不知归路
    2021-02-11 05:01

    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}})
                }
            }
          }
        })
    

提交回复
热议问题