我可以获取从Firestore集合组查询中获取的文档的路径或引用吗



所以我想像这样执行收集组查询,以在收件箱中获取所有过期的邮件文档

const oneMonthAgo = moment().subtract(1, "month").toDate();
db.collectionGroup("inbox")
.where("createdAt", "<", oneMonthAgo)
.get();

inbox实际上是users集合中的一个子集合,因此路径如下:

users/{userID}/inbox/{messageID}

在我使用上面的集合组查询代码获得所有过期消息后,我需要删除所有过期消息。要删除消息文档,我需要知道文档的路径/引用

我可以从消息文档中的字段中获取消息ID。但我不知道用户ID是,所以我不知道删除消息的完整路径/引用

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

那么我可以从上面的集合组查询代码的结果中获得userID吗?因为我需要使用此代码删除消息文档

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

上面的代码将返回CCD_ 3的承诺。我需要获取从集合组查询中获得的文档的路径或引用。

我能那样做吗?

给定一个消息文档,您可以通过遍历其引用的parent链来确定用户:

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
});

另请参阅如何在Firestore中基于子集合文档值返回父集合?