【问题标题】:Get a sub-collection's parent-document's id获取子集合父文档 id
【发布时间】:2020-05-16 14:44:49
【问题描述】:

考虑下图:

我正在用 Node.js 编写一个云函数,并创建了一个函数,当用户在 messageRoom 中写入消息时会触发该函数。当函数被触发时,它会在messages 子集合中生成消息文档的快照。

有没有办法让我获得父文档的 id,例如 2AelOkjccuGsfhXIcjWR,它包含正确的子集合?

【问题讨论】:

  • 请编辑问题以显示您到目前为止编写的代码。如果我们看到您的位置,就会更容易回答这个问题。
  • @DougStevenson 感谢您的提示。我想让这个问题尽可能笼统。下次我问问题时会记住你的提示
  • 编程时会遇到很多错误 - 在 Stack Overflow 上,查看代码总是很有帮助,因为可能存在与您不同的问题怀疑。

标签: firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

如果您的函数在“当用户在 messageRoom 中写入消息时”被触发,则文档路径应类似于 messageRooms/{roomId}/messages/{messageId},云函数应如下所示。然后您可以使用上下文对象并简单地执行context.params.roomId

exports.getParentId = functions.firestore
    .document('messageRooms/{roomId}/messages/{messageId}')
    .onCreate((snap, context) => {
        const parentDocId = context.params.roomId;
        console.log(parentDocId);
        //...
     })

如果您的云函数不同并且您不能使用context,另一种解决方案是一方面使用DocumentReferenceparent 属性,另一方面使用CollectionReference 的属性。

类似:

    const snapRef = snap.ref;   //Reference of the Document Snapshot
    const messagesCollectionRef = snapRef.parent;  //Reference of the messages collection (i.e. the parent of the Document)
    const roomRef = messagesCollectionRef.parent;  //Reference of the room doc (i.e. the parent of the messages collection)
    const roomId = roomRef.id;   //Id of the room doc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 2019-07-10
    • 2019-10-06
    • 2022-11-16
    • 1970-01-01
    • 2021-09-28
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多