Iron router route page refresh problem

Hi everyone,

I’m working on a messaging app for an assignment and everything’s working, but I have a bug in a function that gets called when the chat page is refreshed.

The function checks the collection for an existing chat between 2 users. If there is a chat, it shows it and if not, it creates a new one. When I refresh the page, the function gets called, but for some reason can’t find any existing chat and creates a new one.

Here is my function:

Router.route('/chat/:_id', function () {
    
    var otherUserId = this.params._id; 
    var filter = {$or:[
                {user1Id:Meteor.userId(), user2Id:otherUserId}, 
                {user2Id:Meteor.userId(), user1Id:otherUserId}
                ]};
    var chat = Chats.findOne(filter);  
    if (!chat){// have to create a new one
        chatId=Meteor.call("addChat",Meteor.userId(),otherUserId);
    }
    else {// there is a chat going already - use that. 
      chatId = chat._id;
    }
    if (chatId){// looking good, save the id to the session
        Session.set("chatId",chatId);
        this.render("navbar", {to:"header"});
        this.render("chat_page", {to:"main"}); 
}
 
});

I’m not really sure what’s going on here. I’ve played around and I can see that on a refresh, all the variables get defined with the exception of “var chat = Chats.findOne(filter)” which returns undefined. This doesn’t make much sense to me since I can return Chats.find() to the console and find the document that matches the filter manually.

If anyone could point me in the right direction, I’d really appreciate it.

I see you call server method to add a document, so you removed “insecured” and even “autopublish”? If yes, you have to use publication and subscription

Yep, I’ve removed both packages and have the publication and subscriptions set up. Everything is being stored as expected and the app is usable. It’s just when I have a chat page open and hit refresh that the function doesn’t find the existing data.

You tried exactly your filter to the console and it worked? Or maybe your subscription has not been ready when this “Chats.findOne(filter);” executed

As @gunner13 mentioned your subscription is not ready when you call Chats.findOne. You’ll want to either look into using Iron Routers Wait and Ready subscription options, or move this functionality (and your subscription handling) out of the router.

That’s what I thought initially as well. But within the function, if I add “console.log(Chats.find())” just before, it gives me the list of the documents in the collection. If I change it to “console.log(Chats.findOne())” without a filter it goes back to undefined. I’m a bit confused…

@hwillson - good point. I’ll have a look into those options but it might be better to move this part of the code to another part.

Thanks

I put in a wait list and it works perfectly now - thanks a lot @hwillson