首页 > 解决方案 > firebase.firestore.FieldValue.serverTimestamp() 在我尝试插入时创建一个“修改后的”快照条目

问题描述

抱歉,我不知道这是一个问题,还是我无法以正确的方式使用它,

我面临的问题是..

我正在尝试创建一个新文档,其中包含某些字段,并创建了一个字段,当我尝试使用 onSnapshot() 侦听器检索新输入的文档时出现问题。onSnapshot() 侦听器被触发两次,添加了类型,然后触发了类型modified,因为firebase.firestore.FieldValue.serverTimestamp()的值 没有同时插入。

这是添加文档的代码片段

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

这是阅读文档的代码:

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

这是控制台屏幕截图:- 错误

标签: javascriptfirebaseionic-frameworkgoogle-cloud-firestore

解决方案


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

推荐阅读