Casper Koch
Casper Koch

Reputation: 133

Get a sub-collection's parent-document's id

Consider the following image:

enter image description here

I am writing a cloud function in Node.js and have created a function that gets triggered when a user writes a message in a messageRoom. When the function is triggered it has a snapshot of the message document in the messages sub-collection.

Is there a way for me to get the id of the parent document e.g 2AelOkjccuGsfhXIcjWR, which contains the right sub-collection?

Upvotes: 2

Views: 773

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

If your function is triggered "when a user writes a message in a messageRoom" the document path should be like messageRooms/{roomId}/messages/{messageId} and the Cloud Function should look as follows. You can then use the context Object and simply do context.params.roomId.

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

If your Cloud Function is different and you cannot use context, another solution consists in using the parent properties of the DocumentReference on one hand, and of the CollectionReference, on the other hand.

Something like:

    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

Upvotes: 3

Related Questions