繁体   English   中英

如何使用 JavaScript 根据 Cloud Firestore 中的查询删除数组中的 object

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

我想根据 Cloud Firestore 中使用 JavaScript 的查询删除数组中的 object

这是我的数据库的结构: 在此处输入图像描述

数组是“reserved_items”,里面有多个对象。 如果 object 中的“uniqueBarcode”与“Barcode”匹配,我想删除其中一个对象

这是我到目前为止所尝试的:

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”是条形码的值

一般来说,如果您打算单独查询它们的元素,请不要将 arrays 存储在 Firestore 或 RTDB 中。 而是将reserved_items存储为子集合并使用唯一的条形码作为它们的键,然后您可以像这样删除单个文档:

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

但是,要回答您的特定问题,您需要检索数组,在客户端对其进行修改,然后将其保存回您的文档。

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!");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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