Ad

Firebase.firestore.FieldValue.serverTimestamp() Creates A "modified" Snapshot Entry While I Am Trying To Insert It

Sorry , I am not aware that ,is this a issue, or I am not able to use it in the correct manner,

The problem I am facing is ..

I am trying to create a new document , with certain fields , with one field being created ,the issue comes when I'm trying to retrieve the newly entered document with a onSnapshot() listener. The onSnapshot() listener gets triggered twice once with the type added and just after that with the type modified , just because the value of firebase.firestore.FieldValue.serverTimestamp() is not inserted at the same time.

Here is the code snippet for adding the document

            senderid : this.buddy.senderId,
            receiverid: this.buddy.receiverId,
            message : msg,
            created: firebase.firestore.FieldValue.serverTimestamp()

And here is the code for reading the documents:

   this.db.collection(this.collectionName.friendsCollection).doc(this.buddy.docid)
     .collection(this.collectionName.chatsCollection).orderBy('created')
     .onSnapshot(snapshot=> {
       skip.buddymessages = [];
       if(snapshot.empty)
       {
         console.log("First Chat");
       }
       else{
         console.log("size",snapshot.size)
         snapshot.docChanges.forEach(change => {
           if (change.type === 'added') {
             console.log('New : ', change.doc.data());
           }
           if (change.type === 'modified') {
             console.log('Modified : ', change.doc.data());
           }
           if (change.type === 'removed') {
             console.log('Removed : ', change.doc.data());
           }
         });

Here is the console screenshot:- Error

Ad

Answer

What you are seeing is the expected behavior. The client sees its own document information the moment it's added (your 'added' callback - this is considered an event for a local change), but since the timestamp is computed on the server, that timestamp is written later on the server, and is eventually synchronized back to the client (your 'modified' callback). The linked documentation shows how to tell if a snapshot has a pending write that hasn't been fully committed on the server.

Retrieved documents have a metadata.hasPendingWrites property that indicates whether the document has local changes that haven't been written to the backend yet. You can use this property to determine the source of events received by your snapshot listener:

db.collection("cities").doc("SF")
    .onSnapshot(function(doc) {
        var source = doc.metadata.hasPendingWrites ? "Local" : "Server";
        console.log(source, " data: ", doc.data());
    });
Ad
source: stackoverflow.com
Ad