首页  >  文章  >  web前端  >  如何在不覆盖的情况下更新 Firestore 中的数组:“arrayUnion”和“arrayRemove”指南

如何在不覆盖的情况下更新 Firestore 中的数组:“arrayUnion”和“arrayRemove”指南

Patricia Arquette
Patricia Arquette原创
2024-10-25 08:08:02337浏览

How to Update Arrays in Firestore Without Overwriting: A Guide to `arrayUnion` and `arrayRemove`

在 Firestore 中轻松更新数组

使用 Firestore 时,您可能会遇到需要更新文档中的数组的情况。虽然这似乎是一项简单的任务,但要完美地实现它,需要了解 Firestore 的特定功能。

传统上,尝试使用 .set() 和 merge: true 或 .update() 等技术更新数组通常会导致结果覆盖数组的内容。不过,Firestore 现在提供了两个优雅的函数,使您能够无缝添加和删除数组元素:

  • arrayUnion():有选择地向数组添加元素,确保避免重复。
  • arrayRemove():有效地从数组中删除所有出现的指定元素。

例如,假设您有一个具有以下结构的文档:

{
  proprietary: "John Doe",
  sharedWith: [
    {who: "[email protected]", when: timestamp},
    {who: "[email protected]", when: timestamp},
  ],
}

要向 shareWith 数组添加新条目,可以使用以下语法:

<code class="javascript">firebase.firestore()
  .collection('proprietary')
  .doc(docID)
  .update({
    sharedWith: firebase.firestore.FieldValue.arrayUnion(
      {who: "[email protected]", when: new Date()}
    )
  });</code>

类似地,要从数组中删除元素,请使用以下方法:

<code class="javascript">firebase.firestore()
  .collection('proprietary')
  .doc(docID)
  .update({
    sharedWith: firebase.firestore.FieldValue.arrayRemove({who: "[email protected]"})
  });</code>

通过利用这些专用函数,您可以放心地更新 Firestore 文档中的数组,而不必担心不必要的覆盖。请记得参阅 Firestore 官方文档以获取详细示例和特定场景的指导。

以上是如何在不覆盖的情况下更新 Firestore 中的数组:“arrayUnion”和“arrayRemove”指南的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn