【问题标题】:How to set only ONE element in an array in firebase如何在firebase的数组中只设置一个元素
【发布时间】:2018-09-20 15:15:49
【问题描述】:

我的 firebase 上保存了一个数组,如下所示:

matches:[ {match:{id:1,data:...}}]

我只想在这个数组的 firebase 上保存一项。例如,我的比赛有 id:32。我想在 firebase 中保存的数组上找到它,然后更改它。

我正在努力做到这一点。但我认为向火力库发出请求、复制数组并再次保存整个数组是非常难看的。

const ref = `/users/${currentUser.uid}/matches`;
      var list = [];
       firebase.database().ref(ref).on('value',  function (snap) { list = snap.val(); });

  if (list.length > 0) {
    const indexToUpdate = list.findIndex(k => k.name == match.name)
    if (indexToUpdate >= 0) {
      list[indexToUpdate] = match;

      return dispatch => {

         firebase
          .database()
          .ref(`/users/${currentUser.uid}/matches`)
          .set(list)
          .then(() => {
            dispatch({ type: MATCH_UPDATE, payload: match });
          });

      };
    }
  }

有灯吗?

【问题讨论】:

  • 您尝试了吗/users/${currentUser.uid}/matches/${indexToUpdate}/Firebase 将数组存储为对象,并在返回客户端时将其转换回数组跨度>

标签: javascript reactjs firebase firebase-realtime-database


【解决方案1】:

这行代码:

const indexToUpdate = list.findIndex(k => k.name == match.name)

你的数据结构并不理想,这是一个致命的赠品。

考虑将匹配项存储在其名称下,并在其前面加上一个字符串,以防止 Kenneth 提到的数组强制转换。所以:

matches
  match1
    date: "2018-06-14..."
    ...
  match2
    date: "2018-06-16..."
    ...

有了这个,您可以在不需要查询的情况下查找匹配的节点。它还阻止使用数组,正是由于您提到的原因,这在 Firebase 中是一种反模式。

有关这方面的更多信息,请参阅 Best Practices: Arrays in Firebase 上的经典 Firebase 博客文章。

【讨论】:

    【解决方案2】:

    Firebase 将数组存储为对象,如果键的数字顺序正确,则在返回客户端时将其转换回数组

    但基本上它应该能够在您创建要更新的对象的路径时工作。

    firebase
      .database()
      .ref(`/users/${currentUser.uid}/matches/${indexToUpdate}`)
      .set(match)
      .then(() => {
        dispatch({ type: MATCH_UPDATE, payload: match });
      });
    

    【讨论】:

    • 但是要更新的索引不是数组中的位置吗?例如,我的比赛有 id:2 但在我的火力基地的数组的位置 0。如果不检查 id,我怎样才能找到这个数组的位置?
    • 要更新的索引应该是数组中的位置。 const indexToUpdate = list.findIndex(k => k.name == match.name)你已经在这里找到了索引。
    • 所以,我需要先获取数组,获取索引,然后设置,对吧?
    • 是的,您需要先获取数组。
    【解决方案3】:

    您需要通过 URL 中的 ID 引用您尝试设置的项目的 ID

         firebase
          .database()
          .ref(`/users/${currentUser.uid}/matches/32`)
          .set(list)
          .then(() => {
            dispatch({ type: MATCH_UPDATE, payload: match });
          });
    

    此外,如果索引不起作用,请使用 snap.key 获取所需的 ID。

    【讨论】:

    • 我上传了我的 firebase 的屏幕截图:问题是,如何设置与“match.name==2”的匹配。在这种情况下,他在数组中的索引是 1
    • 你需要 snap.key,而不仅仅是 snap.val()
    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 2022-01-11
    • 2012-10-04
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多