问题
I have a problem with deleting an Object out of an Array in firestore.
I have this data in firestore:
And now I would like to delete e.g the second Object out of the posts Array.
Code:
deletePic () {
let docId = `${this.currentUser.uid}`
fb.usersCollection.doc(docId).update({
posts: firebase.firestore.FieldValue.arrayRemove()
})
.catch(function(error) {
console.error("Error removing document: ", error);
});
}
But I do not know how to define arrayRemove()
These are the pictures and each one has a delete button to delete the picture.
回答1:
Can't you use filter ? And then return the new posts array to your fb.usersCollection method
//deleteId is the id from the post you want to delete
posts.filter(post => post.id !== deleteId);
edit : So This should be something like :
deletePic (deleteId) {
let docId = `${this.currentUser.uid}`
//deleteId is the id from the post you want to delete
fb.usersCollection.doc(docId).update({
posts: posts.filter(post => post.id !== deleteId);
})
.catch(function(error) {
console.error("Error removing document: ", error);
});
}
回答2:
You could also use the arrayRemove method from the FieldValue helper.
docRef.update({
array: FieldValue.arrayRemove('idToRemove');
});
https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html
来源:https://stackoverflow.com/questions/52150386/how-to-delete-object-from-array-in-firestore