繁体   English   中英

获取子集合的父文档的 id

[英]Get a sub-collection's parent-document's id

考虑下图:

在此处输入图像描述

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

有没有办法让我获取父文档的 ID,例如2AelOkjccuGsfhXIcjWR ,其中包含正确的子集合?

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

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

如果您的云 Function 不同并且您不能使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM