skip to Main Content

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. )

  1. 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()
    });
    
  2. In client side(main.js), I use onSnapshot to listen a change in Firestore. However, I don’t know how to console.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


  1. 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.

    Login or Signup to reply.
  2. I think you’re looking for:

    firebase.firestore().collection('script').orderBy("timestamp", "desc").limit(1)
        .onSnapshot(function(querySnapshot) {
          querySnapshot.forEach(function(doc) {
            console.log("Current data: ", doc.data());
          });
        });
    

    If you want to only get new documents after attaching the listener, you can set the query to only return results after “now” with:

    firebase.firestore().collection('script').orderBy("timestamp", "desc").startAt(new Date()).limit(1)
        .onSnapshot(function(querySnapshot) {
          querySnapshot.forEach(function(doc) {
            console.log("Current data: ", doc.data());
          });
        });
    
    Login or Signup to reply.
  3. The snapshot has a key attribute. You should be able to get the key via doc.key

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search