首页 > 解决方案 > 带有firestore的云功能找不到任何数据

问题描述

我是 js 和 firestore(以及整个 firebase 生态系统)的新手

我想用 2 个字段(account_id,device_id)查询数据,但我总是得到“找不到文档”

let selectQuery = admin.firestore().collection("devices");
    selectQuery.where("account_id", "==", context.auth.uid);
    selectQuery.where("device_id", "==", deviceId);

    selectQuery.get().then(function(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 "asd";
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

我什至尝试删除 where 子句,但是仍然找不到数据,但它就在那里:

在此处输入图像描述

来自上下文和数据的参数是 // UID = UIDwFK2JVghw8XjVGqlEE0Uj09irGK2 // DEVICE_ID = 552cbe50f935de7a

作为请求这里是完整的代码:

exports.authDevice = functions.https.onCall((data, context) => {
    if (!context.auth) {
        // Throwing an HttpsError so that the client gets the error details.
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
            'while authenticated.');
    }

    const deviceName = data.device_name;
    const deviceId = data.device_id;
    const isQR = data.is_qr;
    const uid = context.auth.uid;

    console.log("DEVICE NAME: " + deviceName);
    console.log("DEVICE ID: " + deviceId);
    console.log("is QR: " + isQR);
    console.log("UID: " + uid);

    admin.firestore().collection("devices")
        .where("account_id", "==", context.auth.uid)
        .where("device_id", "==", deviceId)
        .get().then(function(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 "asd";
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
});

标签: javascriptfirebasefirebase-authenticationgoogle-cloud-firestoregoogle-cloud-functions

解决方案


经过一些调试,我发现它没有返回单个文档,而是返回一个“QUERY SNAPSHOT”,其方法为空或大小。

更改后:

return admin.firestore().collection("devices").where("account_id", "==", context.auth.uid)
        .where("device_id", "==", deviceId).get().then((snapshot) => {
        snapshot.forEach((doc) => {
            console.log(doc.id, '=>', doc.data());
        });
        console.log("Empty: " + snapshot.empty);
        console.log("Size: " + snapshot.size);
        return "asd"
    })
        .catch((err) => {
            console.log('Error getting documents', err);
        });

推荐阅读