首页 > 解决方案 > Firebase Cloud Firestore 如何设置 snapShotOptions

问题描述

我正在为 Firebase 和 Firestore 使用 Node SDK。

当我使用 collection.add() 时,我正在使用以下方法在我的文档上设置时间戳:

firebase.firestore.FieldValue.serverTimestamp()

我的问题是我正在使用 collection.onSnapshot 监听更改,并且时间戳被返回为 null,因为我相信所报告的更改是本地更改,即。数据库还没有时间写时间戳。

我相信添加了firebase.firestore.onSnapshotOptions来解决这个问题。您可以设置为“估计”以在本地更改的快照中返回估计的时间戳 - 稍后在服务器更改中返回的实际时间戳。

我的问题是,如何/在哪里在我的应用程序中设置此选项?

标签: node.jsfirebasegoogle-cloud-firestore

解决方案


我遇到了同样的问题并找到了解决方案。您在将快照转换为数据时设置选项。见例子。

db.collection("cities")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.docChanges().forEach(function(doc) {
            // Use the server timestamps in the .data() method
            console.log(doc.id, " => ", doc.data({ serverTimestamps: 'estimate' }));
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

我会说文档在这方面不是很清楚,并已发送反馈以查看他们是否可以添加示例。


推荐阅读