首页 > 解决方案 > Firebase 服务器时间戳的空对象

问题描述

我得到一个空对象admin.firestore.FieldValue.serverTimestamp(),下面是存储在 Firestore 中的文档的屏幕截图:

在此处输入图像描述

这是创建消息对象的代码(对应于上面的屏幕截图):

import {Message} from "./Message";
import {MessageType} from "./MessageType";
import * as admin from "firebase-admin";

export class TextMessage extends Message {
    constructor(objectID: string,
                content: string,
                authorName: string,
                authorID: string,
                authorPhotoUrl: string,
                createdAt: FirebaseFirestore.FieldValue = admin.firestore.FieldValue.serverTimestamp()) {
        super(objectID,
            content,
            authorName,
            authorID,
            authorPhotoUrl,
            MessageType.text,
            createdAt,)
    }
}

这是我创建TextMessage对象的地方:

 const message: TextMessage = new TextMessage(
            messageID,
            "Cualquier consulta escríbeme un mensaje y estaré para ayudarte",
            SUPPORT_NAME,
            SUPPORT_USER_ID,
            defaultProfilePicture
        )

这是使用上述代码的 Firebase 函数代码:

// Create the chat
    const createChatPromise =
        firestoreDB
            .collection("Chats")
            .doc(chatID)
            .collection("Messages")
            .add(JSON.parse(JSON.stringify(message)))

 // Return the method when both functions are finished
    return Promise.all(
        [
            addToFirestorePromise,
            addToAlgoliaPromise,
            emailPromise,
            createCurrentUserInboxPromise,
            createSupportInboxPromise,
            createChatPromise, ==> This is the promise from above
            addUsersIDsPromise
        ]
    ).catch(error => functions.logger.log("The error is: " + error.message))

从对象的文档中:

返回与 set()、create() 或 update() 一起使用的标记,以在写入的数据中包含服务器生成的时间戳。

返回: 用于调用 set()、create() 或 update() 的 FieldValue 标记。

但是,我正在使用该add功能,我不知道这是否是无法正常工作的原因。

注意:我将以下版本用于 firebase 管理员和功能:

"firebase-admin": "^8.10.0",
"firebase-functions": "^3.7.0",

标签: node.jsfirebaseservergoogle-cloud-functionsfirebase-admin

解决方案


我不清楚你为什么像这样同时使用 stringify 和 parse :

JSON.parse(JSON.stringify(message))

stringify 将销毁内部表示服务器时间戳的令牌。您应该将要存储在 Firestore 中的对象直接传递给add()set()- 永远不要对其进行字符串化。


推荐阅读