randomUser786
randomUser786

Reputation: 1655

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. 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

Upvotes: 0

Views: 574

Answers (2)

John
John

Reputation: 11399

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

Upvotes: 1

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

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)){..

Upvotes: 1

Related Questions