返回

在 Firebase 数组中畅游自如:创建、更新和删除元素指南

vue.js

## Firebase 数组中的元素操作指南

在 Firebase 的云端文件中,数组是一种强大的数据类型,它可以让你存储和处理成对数据。如果你使用 Vue.js 框架来构建 Firebase 应用程序,了解如何在数组中创建、更新和删除元素至关重要。

### 创建元素

要创建一个新元素并将其添加到数组的末尾,使用 arrayUnion 方法:

const cityRef = doc(db, "cities", "BJ");

await updateDoc(cityRef, {
  regions: arrayUnion("west_coast")
});

### 更新元素

要更新数组中的元素,可以结合使用 arrayRemovearrayUnion 方法:

const cityRef = doc(db, "cities", "BJ");

await updateDoc(cityRef, {
  regions: arrayRemove("west_coast"),
  regions: arrayUnion("east_coast")
});

### 删除元素

要从数组中删除元素,使用 arrayRemove 方法:

const cityRef = doc(db, "cities", "BJ");

await updateDoc(cityRef, {
  regions: arrayRemove("east_coast")
});

### 使用 Vue.js 示例

在 Vue.js 应用程序中操作 Firebase 数组,请考虑以下示例:

<template>
  <div>
    <button @click="addRegion">添加地区</button>
    <button @click="updateRegion">更新地区</button>
    <button @click="deleteRegion">删除地区</button>
  </div>
</template>

<script>
import { ref } from 'vue'
import { projectFirestore } from '../firebase/config'
import { doc, updateDoc, arrayUnion, arrayRemove } from "firebase/firestore";

export default {
  setup() {
    const error = ref(null)
    const isPending = ref(false)

    const docRef = doc(projectFirestore, "cities", "BJ");

    const addRegion = async () => {
      try {
        const res = await updateDoc(docRef, {
          regions: arrayUnion("new_region")
        });
        isPending.value = false;
        return res;
      } catch (err) {
        isPending.value = false;
        console.log(err.message);
        error.value = '无法添加地区';
      }
    };

    const updateRegion = async () => {
      try {
        const res = await updateDoc(docRef, {
          regions: arrayRemove("old_region"),
          regions: arrayUnion("new_region")
        });
        isPending.value = false;
        return res;
      } catch (err) {
        isPending.value = false;
        console.log(err.message);
        error.value = '无法更新地区';
      }
    };

    const deleteRegion = async () => {
      try {
        const res = await updateDoc(docRef, {
          regions: arrayRemove("new_region")
        });
        isPending.value = false;
        return res;
      } catch (err) {
        isPending.value = false;
        console.log(err.message);
        error.value = '无法删除地区';
      }
    };

    return { error, isPending, addRegion, updateRegion, deleteRegion };
  }
}
</script>

### 常见问题解答

1. 如何访问数组中的元素?

答:不能直接从 Firebase 数组中访问元素。相反,你可以使用 get 方法来获取整个数组。

2. 如何设置数组的默认值?

答:在 doc.setdoc.update 中使用 arrayUnion 来设置数组的初始值。

3. 如何同时向数组中添加多个元素?

答:你可以传递一个包含多个元素的数组给 arrayUnion 方法。

4. 如何替换整个数组?

答:使用 set 方法,将新数组值分配给数组字段。

5. 如何对数组进行排序?

答:Firebase 中的数组无法排序。你可以在客户端对它们进行排序,或在查询中使用 orderBy 来排序包含数组的文档。