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.