简体   繁体   中英

How to delete an object in an array based on a query in Cloud Firestore using JavaScript

I would like to delete an object in an array based on a query in Cloud Firestore using JavaScript

This is the structure of my DB: 在此处输入图像描述

The Array is "reserved_items" and it has multiple objects in there. I would like to delete one of those objects if "uniqueBarcode" matched "Barcode" in the object

Here is what I have tried so far:

viewData = null
    console.log(uniqueBarcode)
    db.collection("users").where("uid", "==", uid).where("Barcode", "==", uniqueBarcode)
        .get()
        .then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                viewData = doc.data().wishlist;
                console.log(viewData)
            });
        })
        .catch((error) => {
            console.log("Error getting documents: ", error);
        });

"uniqueBarcode" is the value of the barcode

In general never store arrays in Firestore or RTDB if you intend on querying their elements individually. Instead store reserved_items as a subcollection and use the unique barcode as their key and then you can delete the individual documents like this:

db.doc(`users/${uid}/reserved_items/${barcode}`).delete().then(
  () => console.log("That was easy")
);

However to answer your specific question you would need to retrieve the array, modify it client-side, then save it back to your document.

const ref = firebase.firestore().doc(`users/${uid}`);

ref.get('reserved_items').then(async (doc) => {
  let arr = doc.data();

  if (arr.reserved_items.length > 0) {
    // Filter out all array elements that match uniqueBarcode
    arr.reserved_items = arr.reserved_items.filter(ele => ele.barcode !== uniqueBarcode);

    // Update Firestore with the filtered array
    await ref.update(arr);
  }

  console.log("Done!");
});

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