I use Firebase Hosting and would like to realize this web app.
(I use Windows 10, Windows Subsystems for Linux, Debian 10.3 and Google Chrome browser. )
-
In Cloud Functions(index.js) I make a new document in Firestore’s
script
collection.admin.firestore().collection('script').add({ text: transcription, timestamp: admin.firestore.FieldValue.serverTimestamp() });
-
In client side(main.js), I use
onSnapshot
to listen a change in Firestore. However, I don’t know how toconsole.log
only new document.If I know the document’s ID(for example,G1pvc5LNojV4X7vfvpkI), I can do this in main.js. However, I don’t know how to write new document’s ID.
firebase.firestore().collection('script').doc('G1pvc5LNojV4X7vfvpkI') .onSnapshot(function(doc) { console.log("Current data: ", doc.data()); });
Could you tell me how to write new document’s ID?
3
Answers
An unfiltered collection query will always return all documents in the collection in the first callback. If you don’t want all documents, you will need to filter for only the ones you want. If you don’t have a filter in mind, then what you’re doing is not possible with snapshot listeners.
Since you are writing a timestamp into each document, you can use that as a filter to get only the newest documents, but that is not necessarily guaranteed to work the way you want. If the date on the client is wrong, then you might not get what you’re looking for.
If you want to notify a specific client of a new document in a collection, you could send a message using FCM, but that will require a lot more work.
I think you’re looking for:
If you want to only get new documents after attaching the listener, you can set the query to only return results after “now” with:
The snapshot has a key attribute. You should be able to get the key via
doc.key