Firestore 在尝试从文档获取数组字段时返回未定义

问题描述 投票:0回答:1

我正在尝试从此 Firestore 文档中获取

players
数组(您可以在屏幕截图中看到),以便通过 POST 调用更新它。

我的问题是,每当我收到此文档时,调用

doc.data().players
doc.get("players")
总是返回未定义。

调试时,我可以看到

doc.data()
包含所有预期的字段和值,所以我不明白为什么我无法获取数组字段,而获取像
doc.data().admin
这样的其他字段却工作正常。

这是我的代码:

export const updatePlayers = async (req, res, next) => {
  try {
    const data = req.body;
    const roomsRef = db.collection("rooms");
    const snapshot = await roomsRef.where("roomId", "==", data.roomId).get();
    const player = req.body.player;
    if (snapshot.empty) {
      console.log("No matching documents.", data.roomId);
      res.status(201).send();
      return;
    }
    console.log("updating players...");

    snapshot.forEach((doc) => {
      const prevPlayers = doc.data().players;
      console.log(doc.data().players, "previous players");
      const newPlayers = [...prevPlayers, player];
      console.log(newPlayers, "new players");
      doc.ref.update({
        players: newPlayers,
      });
      res.status(200).send();
      console.log("players update");
    });
  } catch (error) {
    res.status(400).send(error.message);
  }
};

您发现该方法有什么问题吗?我应该如何获得该字段?

enter image description here

javascript typescript firebase google-cloud-firestore
1个回答
0
投票

尝试这个版本:

export const updatePlayers = async (req, res, next) => {
  try {
    const data = req.body;
    const roomsRef = db.collection("rooms");
    const snapshot = await roomsRef.where("roomId", "==", data.roomId).get();
    const player = req.body.player;
    
    if (snapshot.empty) {
      console.log("No matching documents.", data.roomId);
      res.status(201).send();
      return;
    }

    console.log("updating players...");
    let updatePromises = [];

    snapshot.forEach((doc) => {
      const docData = doc.data();
      console.log("Document data:", docData);
      
      if (!docData.hasOwnProperty('players')) {
        console.log("Players field does not exist in document.");
        res.status(400).send("Players field not found.");
        return;
      }

      const prevPlayers = Array.isArray(docData.players) ? docData.players : [];
      const newPlayers = [...prevPlayers, player];
      console.log("previous players:", prevPlayers);
      console.log("new players:", newPlayers);

      updatePromises.push(doc.ref.update({
        players: newPlayers,
      }));
    });

    await Promise.all(updatePromises);
    res.status(200).send();
    console.log("players update");
  } catch (error) {
    res.status(400).send(error.message);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.