firebase 检索Firestore中嵌套子集合的文档ID

dkqlctbz  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(132)

我在Firebase Firestore中使用了以下结构:

是否可以只查询第二张图片中间列中显示的文档id?这是我当前的查询,在我看来这是最合理的查询方式。console.log返回成功消息,但数组为空:

async function getListofPosts() {
    try{
        return await useFireStore
        .collection('chats')
        .doc(`${postId}`)
        .collection('chat')
        .get().then(res => {
            let theMessageList = [];
            res.forEach(doc => {
                theMessageList.push(doc.data(), doc.id )
            });
            setMessageList(theMessageList);
        });
    }
    catch {
        console.log('error on getListofPosts')
    }
    finally {
        console.log('getListofPosts worked')
    }
}

任何帮助都非常感谢。干杯,马特

lrl1mhuk

lrl1mhuk1#

我遇到了同样的问题,并实施了此解决方案:

app.post('/read-whole-collection', async (req, res) => {
    fireStore.initializeApp({
        credential: fireStore.credential.cert(FS_OBJ)
    });

    const db = fireStore.firestore();
    const { fromTable } = req.body;
    try {
        const adminRef = await db.collection(fromTable).listDocuments();
        const data = adminRef.map((doc, index) => {
            return doc.id;
        });
        res.send({ length: data.length, data });
    } catch (error) {
        console.log({ message: 'read-whole-collection : Something went wrong in reading data', error: error });
        res.send({ message: 'read-whole-collection: Something went wrong in reading data', error: error });
    };
});

输出:

{
    "length": 2465,
    "data": [
        "165ee1c0-98fb-4dba-b813-1b7276d0105e",
        "1UserId",
        "1shubhamverma",
        "1test",
        "2FOAE482A55029DA11ED88A4BB9D819E45AB",
        "3e3f5174e14a2584f12aa9cceaad7a1c",
        "8ffa892a-4dbb-4ad3-8c24-481a6cc4aebc",
        "AAAA",
        "AAAATEST_USER_APP_RATING_1_15DEC_3",
        "APP_MIGRATION",
        "PENDING_ACTION_15DEC_2",
        "USER_10000",
        "20Dec_1",
        "22-11-21",
...
...
...
...
        "411ED86A8CD8A643E1B8D",
        "Users",
        "ea2c7316-7a8f-4066-a5fc-fb4e471aabd9",
        "null"
    ]
}

** Postman 截图:**

ru9i0ody

ru9i0ody2#

相关问题-Firestore Cloud Function empty collection
看起来集合chatschat下的文档是空的(* 文档ID显示为斜体 *)。因此,要解决此问题,请使用collectionGroup查询。

return await useFireStore
        .collectionGroup('chat')
        .get().then(res => {
            let theMessageList = [];
            res.forEach(doc => {
                theMessageList.push(doc.data(), doc.id )
            });
            setMessageList(theMessageList);
});

在使用collectionGroup查询之前,我建议您阅读此查询及其限制-https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query

相关问题