首页 > 解决方案 > Firebase Cloud Firestore doc.data().includes 或 .IndexOf 不起作用

问题描述

我正在尝试使用一个数组,尝试在我存储在云 Firestore 上的数组上运行doc.data().includesdoc.data().indexOf该数组是文档中唯一存在的东西。

数据是这样排列的

    0: example@gmail.com
    1: firebase@gmail.com
    2: new@gmail.com

为了得到我刚刚做的数据

firebase.firestore().collection('mails').doc('emails').get().then((doc) => {
            if (doc.exists) {
                console.log(doc.data()); //prints the list of emails in form of array
                doc.data().IndexOf(email); //error IndexOf doesn't exist
                doc.data().includes(email); //error includesOf doesn't exist
            }
            else {
                console.log('data doesn't exist');

            }

        });

Cloud Firestore 数据库视图

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


要访问doc.data().IndexOfdoc.data().includes或任何其他与数组相关的函数,只需将转换doc.data()为数组,如下所示:

var docArray = Object.values(doc.data());
docArray.includes(stringToSearchFor);

或者

Object.values(doc.data()).includes(stringToSearchFor);

这将允许您运行docArray.includesdocArray.IndexOf. 转换的原因是 firebase 返回作为对象对象的整个文档,您可以通过 console.log(doc.data()) 看到这一点并查看原型字段。发生这种情况是因为 firestore 将数组存储为 json 对象,这意味着您看到的数组索引号实际上不是索引号,它们只是对象键。

意义

0: example@gmail.com
1: firebase@gmail.com
2: new@gmail.com

索引在哪里0, 1, 2(或看起来)并且example@gmail.com, firebase@gmail.com, new@gmail.com是值,但在0, 1, 2实际上只是键的firestore中,它们不是索引。因此,要获取我们刚刚运行的键(数字)或值(电子邮件)Object.keys(doc.data())// will return numbersObject.values(doc.data())//will return emails您将获得所需的数组,现在您可以在该数组上运行操作。


推荐阅读