如何从firestore中的数组中删除对象 [英] How to delete object from array in firestore
问题描述
我在从 firestore
中的 Array
中删除 Object
时遇到问题.我在 firestore 中有这些数据:
I have a problem with deleting an Object
out of an Array
in firestore
.
I have this data in firestore:
现在我想删除例如 posts Array
中的第二个 Object
.
And now I would like to delete e.g the second Object
out of the posts Array
.
代码:
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);
});
}
但是我不知道如何定义arrayRemove()
这些是图片,每一张都有一个删除按钮来删除图片.
These are the pictures and each one has a delete button to delete the picture.
推荐答案
警告不要使用我的解决方案,因为它已经超过 3 年了,现在有新的解决方案:https://stackoverflow.com/a/59745086/6668441 我的是纯 js 的,是一个糟糕的模式.
Warning Do not use my solution as it is more than 3 years old, nowadays there is new solution : https://stackoverflow.com/a/59745086/6668441 Mine was a pure js one and is a bad pattern.
你不能使用过滤器> ?然后将新的帖子数组返回到您的 fb.usersCollection
方法
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);
所以这应该是这样的:
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);
});
}
这篇关于如何从firestore中的数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!