You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

markFavorite函数仅能添加一个收藏元素,添加第二个触发FirebaseError

问题排查:Firebase updateDoc 添加数组元素报错

问题现象

markFavorite函数仅能向favorites数组添加一个元素,尝试添加第二个新元素时触发如下报错;重复添加同一元素则无问题。

FirebaseError: Function updateDoc() called with invalid data.
Unsupported field value: undefined (found in document users/l2c8ieJurAfrqI1Pj6wNWro1S2u2)

原函数代码:

async function markFavorite(did, nombre, comentarios, valor) {
  try {
    const docRef = doc(db, "users", auth.currentUser.uid);
    const docSnap = await getDoc(docRef);
    if (docSnap.exists()) {
      console.log("Document.data:", docSnap.data());
      const favoriteUpdate = {
        favorite: true,
        id: did,
        nombre: nombre,
        comentarios: comentarios,
        valor: valor,
      };
      let favoritesUpdate;
      const favorites = docSnap.data().favorites;
     // Checking if the array is empty or not. If it is empty, it will add the new item to the array.
     // If it is not empty, it will check if the item is already in the array. If it is, it will update
     // the item. If it is not, it will add the new item to the array.
      if (favorites && favorites.length) {
        const findAuto = favorites.find((item) => item.id === did);
        if (findAuto) {
          favoritesUpdate = favorites.map((item) =>
            item.id === did ? favoriteUpdate : item
          );
        } else {
          // Adding the new item to the array.
          favoritesUpdate = [...favorites, favoritesUpdate];
        }
      } else {
       // Adding the new item to the array.
        favoritesUpdate = [favoriteUpdate];
      }

      // Updating the document with the new array.
      await updateDoc(docRef, {
        favorites: favoritesUpdate,
      });
      alert("¡Añadido a tus favoritos!");
    } else {
      console.log("No se localiza este documento!");
    }
  } catch (error) {
    console.log(error);
  }
}

错误原因

问题出在添加新元素的分支中:

favoritesUpdate = [...favorites, favoritesUpdate];

此处错误地将未赋值的favoritesUpdate变量本身拼接到数组中,此时favoritesUpdate还是undefined,导致updateDoc接收到包含undefined的数组,触发“不支持undefined字段值”的报错。

修复方案

将上述错误行中的favoritesUpdate替换为要添加的目标对象favoriteUpdate:

修正后的完整代码:

async function markFavorite(did, nombre, comentarios, valor) {
  try {
    const docRef = doc(db, "users", auth.currentUser.uid);
    const docSnap = await getDoc(docRef);
    if (docSnap.exists()) {
      console.log("Document.data:", docSnap.data());
      const favoriteUpdate = {
        favorite: true,
        id: did,
        nombre: nombre,
        comentarios: comentarios,
        valor: valor,
      };
      let favoritesUpdate;
      const favorites = docSnap.data().favorites;
      if (favorites && favorites.length) {
        const findAuto = favorites.find((item) => item.id === did);
        if (findAuto) {
          favoritesUpdate = favorites.map((item) =>
            item.id === did ? favoriteUpdate : item
          );
        } else {
          // 修正:使用favoriteUpdate而非未初始化的favoritesUpdate
          favoritesUpdate = [...favorites, favoriteUpdate];
        }
      } else {
        favoritesUpdate = [favoriteUpdate];
      }

      await updateDoc(docRef, {
        favorites: favoritesUpdate,
      });
      alert("¡Añadido a tus favoritos!");
    } else {
      console.log("No se localiza este documento!");
    }
  } catch (error) {
    console.log(error);
  }
}

额外优化建议

可以在获取favorites时默认赋值空数组,简化判断逻辑:

const favorites = docSnap.data().favorites || [];
// 之后直接判断favorites.length即可
if (favorites.length) {
  // ...原有逻辑
} else {
  favoritesUpdate = [favoriteUpdate];
}

内容的提问来源于stack exchange,提问作者Dirk Gaston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:05:33