Bil5
Bil5

Reputation: 502

Firestore, detecting a new document added to a collection, and more

Listening to documents changes on a Firestore Document is quite easy and works well.

I'm wondering though if there's any way to listen to a collection in a way we get notified when a document belonging to this collection is added/updated/deleted.

So far we can know everything that happens to a known document, but of course if it's a new document we definitely have no way to create in advance a listener on this document. Moreover, even if we were able to know in advance the new documents IDs, it's obvious that creating as many listeners as documents we have in a collection would be absolutely a bad practice.

My question in not specific to any language but for information I'm using flutter.

Does Firestore ecosystem provide a way to achieve this? Thanks in advance.

Upvotes: 1

Views: 1513

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

if it's a new document we definitely have no way to create in advance a listener on this document

That's not really true. You can construct a query that would yield a document before that document exists. A listener on that query will show the document as added in the event that it's created, and also satisfies the constraints of the query.

I don't know if flutter has very good documentation for this, but the core documentation for realtime updates shows how you can get snapshot changes when the results of a query change. Note that you can check the resulting query snapshot for documents that have been added, removed, or changed since the prior snapshot that was delivered to the listener.

The trick is to come up with a query that will tell you what you want to know. You will have to populate the document with enough information so that a listener can tell that it's a document of interest that was just created.

Upvotes: 2

Related Questions