I have an array that contains the documents id of the firebase. I need to click on the button to delete these documents in the firebase.
deletePosts() {
db.collection("users")
.doc(user.email)
.collection("posts")
.doc(this.selectedPosts[0].id)
.delete()
.then(() => {
console.log("Success!");
})
.catch(err => {
console.log(err);
});
}
},
How can I iterate documents and delete them?
You could use a batched write as follows:
deletePosts() {
let batch = db.batch();
this.selectedPosts[0].forEach(element => {
batch.delete(db.collection("users").doc(user.email).collection("posts").doc(element.id));
});
batch.commit()
.then(() => {
console.log("Success!");
})
.catch(err => {
console.log(err);
});
}
Note that a batched write can contain up to 500 operations. In case you foresee that you could have to delete more than 500 you could use Promise.all()
, as follows:
deletePosts() {
const promises = [];
this.selectedPosts[0].forEach(element => {
promises.push(db.collection("users").doc(user.email).collection("posts").doc(element.id).delete());
});
Promise.all(promises);
.then(() => {
console.log("Success!");
})
.catch(err => {
console.log(err);
});
}
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.