【问题标题】:How to delete fields for all documents in Firestore如何删除 Firestore 中所有文档的字段
【发布时间】:2021-09-29 11:29:54
【问题描述】:

我想删除 Firestore 中所有文档的特定字段,我该怎么做? 由于在 Firebase、Stackoverflow 等上没有此问题的文档。我知道可以使用 SDK 删除单个文档的字段,因此我别无选择从 Firestore 获取所有文档并删除每个文档的字段SDK 的 delete() 集合?

例如,如果从 'users' 中删除 'first_name'

之前

Collection : users

Document: A
{
  "id": "A",
  "first_name": "Sid",
  "last_name": "Wilson"
}

Document: B
{
  "id": "B",
  "first_name": "Joey",
  "last_name": "Jordison"
}

Document: C
{
  "id": "C",
  "first_name": "Chris",
  "last_name": "Fehn"
}

之后

Collection : users

Document: A
{
  "id": "A",
  "last_name": "Wilson"
}

Document: B
{
  "id": "B",
  "last_name": "Jordison"
}

Document: C
{
  "id": "C",
  "last_name": "Fehn"
}

【问题讨论】:

  • 是每个文档中的“users”和数组还是数组中的每个对象都是“users”集合的文档?
  • @Dharmaraj 对不起,我写的很混乱,所以我更正了这个例子。我是根据 Firestore 的 json 输出来描述它的。我的问题是从集合中的所有文档中删除特定字段(在本例中为“用户”)。
  • 不幸的是,没有其他办法。您可以尝试运行我在答案中发布的代码。
  • 如果我的回答对您有帮助,您可以接受 (✔) 并点赞 (????)。随时询问更多问题。

标签: firebase google-cloud-firestore


【解决方案1】:

目前在 Firestore 中无法进行批量写入,要更新任何需要引用它的文档,即文档 ID。这意味着您必须阅读所有文档,获取它们的参考并更新它们。

// Reading all documents
const colRef = firebase.firestore().collection("users")
const colSnapshot = await colRef.get()

const delField = {first_name: firebase.firestore.FieldValue.delete()}

// Array of update promises
const updates = colSnapshot.docs.map((doc) => colRef.doc(doc.id).update(delField))
// Run the promises simulatneously
await Promise.all(updates)

它将花费 N 次读取和写入,其中 N 是文档数,但这似乎是唯一的方法。除非您在其他地方有文档 ID 数组(它会阻止读取,因为您已经知道文档 ID)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-09
    • 2020-09-11
    • 1970-01-01
    • 2020-09-08
    • 2019-01-09
    相关资源
    最近更新 更多