can I get the path or reference of the document fetched from Firestore collection group query?

Viewed 295

so I want to perform collection group query like this, to get all expired messages document in inbox

const oneMonthAgo = moment().subtract(1, "month").toDate();

db.collectionGroup("inbox")
.where("createdAt", "<", oneMonthAgo)
.get();

the inbox is actually a sub-collection in the users collection, so the path will be like this:

users/{userID}/inbox/{messageID}

after I get all the expired messages using that collection group query code above, then I need to delete all those expired messages. to delete the message document, I need to know the path/reference of the document

I can get the messageID from the field in the message document. but I don't know the user ID is, so I don't know the full path / reference to delete that message

users/ ?????? /inbox/{messageID}

so can I get the userID just from the result of collection group query code above? because I need to delete the message document using this code

db.doc(`users/${??????}/inbox/${messageID}`).delete()

the code above will return a promise of FirebaseFirestore.DocumentData . I need to get the path or reference of the document that I get from collection group query.

can I do that ?

1 Answers

Given a message document, you can determine the user by walking up the parent chain of its reference:

const messages = await db.collectionGroup("inbox")
  .where("createdAt", "<", oneMonthAgo)
  .get();
messages.forEach((messageSnapshot) => {
  const messageRef = messageSnapshot.ref;
  const inboxRef = messageRef.parent;
  const userRef = inboxRef.parent;
  console.log(userRef.id); // logs the id of the user document this message is for
});

Also see How to return parent collection based on subcollection document value in Firestore?

Related