Casper Koch
Casper Koch

Reputation: 133

Get field from subcollection's parent document

I am creating a message application with Firestore

At the moment i have created a function that gets triggered when a user writes a message in a messageRoom. Each messageRoom document has a subcollection called messages which contains the messages of the room. The messageRoom document itself contains data related to the messageRoom itself e.g. users who are part of the messageRoom. The messageRoom contains a field called members which holds info about the user who are a part of the messageRoom

I want to get access to the data in the messageRoom document and not the messages subcollection. At the moment the following code does not work. An error tells me that the members field is undefined. What have i done wrong?

exports.sendNotification = functions
  .firestore
  .document('messageRooms/{messageRoomId}/messages/{messageId}')
  .onCreate(  
  async (snapshot) => {
    /*
    Does something with the documents in the subcollection
    */

    //Get the DocumentReference of the parent doc
    const parentDocId = snapshot.ref.parent.id;

    admin.firestore().collection('messageRooms').doc(parentDocId).get('members').get().then(doc => {
      if (doc.exists) {
         console.log("Document data:", doc.data());
      } else {
          // doc.data() will be undefined in this case
          console.log("No such document!");
      }
      return; //return added to prevent crash
   }).catch(error => {
      console.log("Error getting document:", error);
   });
  }
);

Upvotes: 1

Views: 755

Answers (1)

vitooh
vitooh

Reputation: 4262

I think the problems is here:

//Get the DocumentReference of the parent doc
    const parentDocId = snapshot.ref.parent.id;

snapshot is DocumentSnapshot, so ref property give us DocumentReference. Property parent of document reference is CollectionReference (Google Doc). So you have to find not parent but "grandparent" :) I may say. Maybe try:

const parentDocId = snapshot.ref.parent.parent.id;

However I would not use .id property here just to get reference in .doc in next line. parent property already provides reference (doc). I don't think that argument in get is changing anything, so I would use .data().messages to get to the field. In the end I would use:

const parentDocRef = snapshot.ref.parent.parent;

    parentDocRef.get().then(doc => { console.log(doc.data().members)})

I hope it will help!

Upvotes: 2

Related Questions