![](/img/trans.png)
[英]How to query documents from a sub-collection, based on a main collection's field and a sub-collection's fields in cloud firestore?
[英]Get a sub-collection's parent-document's id
如果您的 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
,则另一种解决方案包括一方面使用DocumentReference
的parent
属性,另一方面使用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.