【问题标题】:What is the best way to add a new value to an existing array in firebase?向firebase中的现有数组添加新值的最佳方法是什么?
【发布时间】:2021-07-29 05:43:00
【问题描述】:

我正在尝试在 firestore 文档中为每个用户保存不同数量的值(相同类型)。这是使用数组完成的。

当用户决定添加一个新值时,我对需要完成的三个操作中的每一个都有一个函数。

  • 从数据库中获取当前数组并赋值给一个变量
  • 使用 push() 将用户输入添加到数组中
  • 替换数据库中的旧数组
//gets arr from database
  function get() {
    console.log(arr);
    firebase
      .firestore()
      .collection("test")
      .doc("testArray")
      .get()
      .then((doc) => {
        setArr(doc.data().arr);
      })
      .then(() => {
        console.log(arr);
        console.log("value retrieved");
      });
  }

  //adds new object to arr
  function add() {
    arr.push({
      a: 89,
      b: 34,
    });
    console.log("value added");
    console.log(arr);
  }

  //adds arr to database
  function updateArray() {
    firebase
      .firestore()
      .collection("test")
      .doc("testArray")
      .set({
        arr: arr,
      })
      .then(() => {
        console.log("array updated");
      });
  }

我的目标是使用一个函数来运行所有这些操作,这样一键即可完成。

我对异步 js 不是很熟悉,但我已经设法使用 async/await 让前两个函数按顺序运行。

 //gets arr from database
  async function get() {
    console.log(arr);
    await firebase
      .firestore()
      .collection("test")
      .doc("testArray")
      .get()
      .then((doc) => {
        setArr(doc.data().arr);
      })
      .then(() => {
        console.log(arr);
        console.log("value retrieved");
      });

    add();
  }

async function call() {
    await get();
    updateArray();
  }

但是第三个函数似乎仍然先运行,导致在添加新数据之前将数据库中的数据替换为空数组。

【问题讨论】:

    标签: javascript firebase react-native asynchronous google-cloud-firestore


    【解决方案1】:

    要更新 firestore 中的数组,请使用 arrayUnion

    var washingtonRef = db.collection("cities").doc("DC");    
    washingtonRef.update({
        regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
    });
    

    要删除 firestore 中的数组,请使用 arrayRemove

    var washingtonRef = db.collection("cities").doc("DC");
    washingtonRef.update({
        regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
    });
    

    参考:https://cloud.google.com/firestore/docs/manage-data/add-data#update_elements_in_an_array

    【讨论】:

    • 我试试看
    【解决方案2】:
    const db = firebase
    .firestore()
    .collection("test")
    .doc("testArray");
    
    function updateArr() {
    db.update({
      arr: firebase.firestore.FieldValue.arrayUnion(
        {
          a: 2,
          b: 34,
        }
      ),
    });
    

    }

    对于地图内的数组,它只替换当前值。不管 of 如果数组元素具有相同的值

    database values

    【讨论】:

      猜你喜欢
      • 2014-12-17
      • 1970-01-01
      • 2014-07-16
      • 2015-03-12
      • 1970-01-01
      • 2011-03-09
      • 2018-05-27
      • 2014-09-10
      • 2012-04-03
      相关资源
      最近更新 更多