首页 > 解决方案 > 在 Firestore 中设置/添加操作后返回文档数据

问题描述

我正在尝试取回有关我刚刚创建/更新的文档的一些信息,而无需再次请求。

我知道我得到了带有文档 ID 的文档引用,但我需要其他信息,例如 createTime 和 updateTime。

目前,这是我试图实现这一目标的方式,但我想放弃那个额外的请求,因为它不是很有效。

const docRef = await database.collection('tagsCollection').add({
    ...input
    createTime: firestore.FieldValue.serverTimestamp()
});

const doc = await docRef.get();

return {
    ...doc.data(),
    id: doc.id,
    createTime: doc.data().createTime.toMillis().toString()
};

标签: javascriptnode.jsfirebasegoogle-cloud-firestore

解决方案


由于这些字段来自服务器端的 Firestore,因此可以安全地假设客户端在查询 DocumentSnapshot 之前不知道它们是什么。您也许可以自己猜测,但实际上您是在尝试猜测调用add().


推荐阅读