How to detect a brand new document addition to a collection?

Hi,

I am implementing notifications on my webapp using pub/sub. I am also using publish-counts package to get the unread notifications count. I have created a meteorpad sample for review here http://meteorpad.com/pad/dZiD7sq8XkwBGg6Jg/Leaderboard .

I am now trying to have an unread count animate whenever a new notification arrives. I have tried implementing it using observeChanges on Notifications collection. However, it is adding animation class even at the very first loading of subscription. I unsuccessfully tried using Meteor.defer to defer the initialization variable to true.

Can anyone please advise, how can I achieve an animation only when there is a brand new notification in collection?

This is what I’m guessing is happening without looking at your code (sorry, I’m spending wayy… too long answering questions and not working…).

Your notifications collection on your client side starts empty and then you attach observeChanges then meteor starts to sync existing notifications from the server (that you already know about) but observeChanges sees it as a new entry in minimongo and fires.

If not, this may help.

There is no way for observe change to know whether a notification is new or old. All it does is runs a set of functions if the query is returning a different result compared to the last time it ran.

If the data behind your notifications is chronological:

You can timestamp every notification and only query for notifications like so: Notifications.find({timestamp: {$gt: timeOfLastSeen}}). So when your user “acknowledges” that she has seen a notification, you can update the user.lastSeen field to be Date.now(). Now you can be 100% sure that any document added to the above live-query is brand new.

Else, this is useless.

You might consider keeping track of what the user has seen in an array, and then only live query notifications that are not in that array. Then you can be sure the notifications are new since you explicitly checked that none of them were old.