首页 > 解决方案 > 如何正确使用 Firestore 的 serverTimestamp 来设置正在订阅的文档的值?

问题描述

概述/环境:

目标:

观察/错误:

在此处输入图像描述

到目前为止,我已经尝试了这里提到的所有建议:为什么 Firestore 的 'doc.get('time').toMillis' 会产生空类型错误?

似乎没有什么可以解决此崩溃。

这是快照侦听器:

.onSnapshot({ includeMetadataChanges: true }, (querySnapshot) => {
    if (querySnapshot.metadata.fromCache && querySnapshot.metadata.hasPendingWrites) {
    // ignore cache snapshots where new data is being written
      return;
    }
    const messages = [];
    querySnapshot.forEach((doc) => {
        const estimateTimestamps = { serverTimestamps: 'estimate' }
        const msg = doc.data();
        msg.docId = doc.id;
        msg.time = doc.get('time', estimateTimestamps).toMillis();
        const timestamp = doc.get('time', estimateTimestamps);
        if (timestamp) {
          msg.time = timestamp.toMillis();
        } else {
          debugger
          console.error(doc.id + ' is missing "time" field!');
        }

        messages.push(msg);
    });
    dispatch({ type: types.LOAD_MSGS, payload: messages });
    resolve();
});

以下是文档的创建方式:

const addMsg = (msg, userConvos) => {
    return firebase.firestore().collection('messages').add({
        time: firebase.firestore.FieldValue.serverTimestamp(),
        sender: msg.sender,
        read: false,
        userConvos: [userConvos.sender, userConvos.receiver],
        content: {
            type: 'msg',
            data: msg.text
        }
    });
};

我知道该值可能在短时间内为空,我需要一种方法来防止应用程序在此期间崩溃。

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


错误将您指向此代码:

doc.get('time').toMillis()

意思是doc.get('time')返回 null,因此,您不能调用toMillis()它。

您链接到的问题的答案确切地解释了为什么会这样。如果还是不清楚,建议再读一遍。如果服务器时间戳尚未到达服务器,则时间戳将为空。

也许您打算像这样检查时间戳是否为空,而无需调用toMillis()

msg.isPending = doc.get('time') === null;

推荐阅读