javascriptangularjsmeteorangular-meteormeteor-collections

How to validate query result in meteor helper and redirects to 404?


First of all, I am not using Meteor in itself but Angular-Meteor, so the principles are the same. What I need to do is validate in helper function when a resource is valid or not and make a decision based on its result.

I thought find and findOne collection's functions are synchronous in client side, but it seems they are not or I am doing the things in a wrong way.

I have the following code:

this.helpers({
      post() {
        let _post = Posts.findOne({
          _id: this.postId
        });

        if( typeof _post == 'undefined' )
          return this.$state.go('404');

        return _post;
      }
    });

this.postId comes from the Url params. When I am navigating through the app, all work. But when I refresh the page, this.postId is defined but Posts.find() returns undefined and, obviously, it goes to 404 page.

¿How can I make a work-around for this scenario?


Solution

  • It is because when you refresh the page, your view is rendered before data is sent to client. To workaround this, you need to make sure that the data is ready before checking for it existence. In other words, it means to check if your subscription is ready, use this code as a demonstration:

    const handle = Meteor.subscribe('data');
    
    if (handle.ready()) {
      const post = Posts.findOne(/**/);
    
      if (typeof post === 'undefined') {
        console.log('post does not exist');
      }
    }