从Firestore阵列中按键/值删除项目 [英] Remove item by key/value from Firestore array
问题描述
我在Firestore中有一个结构如下的数组:
I have an array in Firestore that is structured like this:
palettes
0: {date: 2019-05-01, name: "First Palette", palette: [array]}
1: {date: 2019-05-02, name: "Palette 2", palette: [array]
调色板
数组中的每个项目都是带有日期的调色板项目,名称,以及调色板数组中的数据。
Each item in the palettes
array is a palette item with date, name, and the palette data in an array.
在我的React应用程序中,我试图通过引用Firestore数据库中的<$ c $来删除特定的调色板。 c> name 的值并且没有运气。
In my React application, I'm trying to delete a specific palette in the Firestore db by referencing its name
value and not having any luck.
例如,如果我有 paletteName
从click事件传入的调色板2,如何删除以该字符串作为名称值的调色板?
For example, if I have the paletteName
"Palette 2" passed in from a click event, how can I delete the palette with that string as the name value?
这是我尝试过的方法:
Here's what I've tried:
1。
const deletePalette = paletteName => {
db.collection('users').doc(user.uid)
.update({
palettes: firebase.firestore.FieldValue.arrayRemove({
name: paletteName
})
})
// ...
}
2。
const deletePalette = paletteName => {
db.collection('users').doc(user.uid)
.update({
palettes: firebase.firestore.FieldValue.arrayRemove(paletteName)
})
// ...
}
3。
const deletePalette = paletteName => {
const ref = db.collection('users').doc(`${user.uid}/palettes/`)
ref.update({
[paletteName]: firebase.firestore.FieldValue.delete()
})
// ...
}
4。
const deletePalette = paletteName => {
db.collection('users').doc(user.uid)
.update({
palettes: palettes.filter(
palette => palette.name !== paletteName
)
})
// ...
}
这些都没有。我在这里想念什么?
None of these are doing it. What am I missing here?
推荐答案
您将无法使用 FieldValue.arrayRemove
。这仅适用于作为数组的顶级字段。您也将无法一次执行此操作。
You won't be able to use FieldValue.arrayRemove
. That only works for top level fields that are arrays. You also won't be able to do this in a single operation.
您将不得不
1 )将整个文档读到内存中,
2)用您想要的方式修改内存中的数组,
3)然后将字段更新回文档。
1) read the entire document into memory,
2) modify the array in memory the way you want,
3) then update the field back to the document.
这篇关于从Firestore阵列中按键/值删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!