简体   繁体   中英

Firestore how do I check if an element exists in an array in cloud firestore using javascript

I would like to check if an element exists in the array in cloud firestore

here is an example element (which is an object):

 var viewData = {ISBN: "8388838", ItemType: "Book", Shelf_Location: "YA FIC German xxx"}

This is the array I am talking about. 这是我正在谈论的数组

Here is the code that I used to check if this element exists in an array in cloud 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);
    });

The code above is not working because when I ran the code console.log(typeof(doc.data().reserved_items)) it returned an object

If you need true / false answer you may use Array.prototype.some() to lookup by ISBN, which is supposed to be unique identifier:

if((doc.data().reserved_items).some(({ISBN}) => ISBN === viewData.ISBN)){..

I think you need to compare the attributes in viewData with the objects in your reserved_items .

The reason you cannot use includes() is because the objects are not the same (even though they contain the same information.)

Consider the following example

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

You could use the find() function, or as mentioned in the comment, the some() function. Below, I used the find() function:

const foundItem = reserved_items.find(item => {
 if(item.ISBN === viewData.ISBN){
  return item;
 }
});
if(foundItem) {
// viewData exists in reserved_items
}

Here is how to use the find()-function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM