[英]How to delete a Firestore collection with cloud functions using javascript
[英]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.