javascript - Firebase Cloud Firestore doc.data().includes 或 .IndexOf 不起作用
问题描述
我正在尝试使用一个数组,尝试在我存储在云 Firestore 上的数组上运行doc.data().includes
,doc.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');
}
});
解决方案
要访问doc.data().IndexOf
或doc.data().includes
或任何其他与数组相关的函数,只需将转换doc.data()
为数组,如下所示:
var docArray = Object.values(doc.data());
docArray.includes(stringToSearchFor);
或者
Object.values(doc.data()).includes(stringToSearchFor);
这将允许您运行docArray.includes
和docArray.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 numbers
,Object.values(doc.data())//will return emails
您将获得所需的数组,现在您可以在该数组上运行操作。
推荐阅读
- reactjs - 如何在不从 tabnavigator 的选项卡之一导航到屏幕的情况下打开抽屉?
- python - 在已安装 Python 3.7 的情况下安装 Anaconda
- python - NLP 生成按列中的值分组的并置三元组数据帧
- kotlin - 从协程获取状态更新
- excel - 如何将一系列数据从一个工作表转移到另一个工作表
- android - 如何在 Koin 的检测测试中注入使用 androidContext 的类?
- r - 根据列/标签重新排序 R 数据框的行
- python - 如何让这个脚本检查目录中的每个文件但不记录每个单独的检查?
- java - 如何通过 css 更改 JavaFX ComboBox 的箭头按钮中的背景颜色?
- c# - 如何将两个不同的控件动态绑定到单个数据网格单元中的两个不同的数据源