![](/img/trans.png)
[英]How to check if a cloud firestore document exists when using realtime updates
[英]Firestore how do I check if an element exists in an array in cloud firestore using javascript
我想检查云火库中的数组中是否存在元素
这是一个示例元素(它是一个对象):
var viewData = {ISBN: "8388838", ItemType: "Book", Shelf_Location: "YA FIC German xxx"}
这是我用来检查此元素是否存在于云 Firestore 中的数组中的代码:
db.collection("users").doc("reservedItemsList").get().then((doc) => {
if ((doc.data().reserved_items).includes(viewData)){
alert("error")
}
}).catch((error) => {
console.log("Error getting document:", error);
});
上面的代码不起作用,因为当我运行代码console.log(typeof(doc.data().reserved_items))
它返回了 object
如果您需要true
/ false
的答案,您可以使用Array.prototype.some()
通过 ISBN 进行查找,这应该是唯一标识符:
if((doc.data().reserved_items).some(({ISBN}) => ISBN === viewData.ISBN)){..
我认为您需要将viewData
中的属性与您的reserved_items
中的对象进行比较。
不能使用includes()
的原因是对象不相同(即使它们包含相同的信息。)
考虑以下示例
const a = {foo:'asd'};
const b = {foo:'123'};
const array1 = [a, b];
console.log(array1.includes({foo:'asd'})); // false
console.log(array1.includes(a)); // true
您可以使用find()
function,或者如评论中所述, some()
function。 下面,我使用了find()
function:
const foundItem = reserved_items.find(item => {
if(item.ISBN === viewData.ISBN){
return item;
}
});
if(foundItem) {
// viewData exists in reserved_items
}
以下是如何使用find() 函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.