简体   繁体   中英

how to write new document's ID [firebase.firestore().onSnapshot()]

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?

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:

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());
      });
    });

The snapshot has a key attribute. You should be able to get the key via doc.key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM