【问题标题】:How can I save multiple messages and save it in separate fields in firestore?如何保存多条消息并将其保存在 Firestore 的单独字段中?
【发布时间】:2021-11-17 05:51:15
【问题描述】:

这是某个用户的firestore文档:

这就是我将要保存在 firestore 中的消息的保存方式:

  const [msg, setMsg] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const userRef = firestore.collection("users").doc(uid);
      const ref = userRef.set(
        {
          msg,
        },
        { merge: true }
      );
      console.log(" saved");
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div>
        <form onSubmit={handleSubmit}>
          <TextField
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
          />
          <Button type="submit">
            Submit
          </Button>
        </form>
    </div>
  );
};

这样,我可以将消息保存在 firestore 中,但是,如果我要发送另一条消息,它将替换之前保存在其中的消息。如何在 Firestore 中保存一条消息并保存另一条消息而不影响上一条消息?

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    我了解到您正在覆盖 users 集合中的同一个文档。这可能是(我们看不到整个代码),因为您没有在两次写入之间更改uid 的值。 uid 是文档 ID,它会被覆盖(即使您使用 { merge: true } 选项,如果 msg 对象包含现有字段,它们也会被覆盖)。

    您提到您保存消息,所以我猜您想为给定用户保存几条消息(该用户由uid 标识)。因此,您可以在用户的​​文档下有一个子集合,并让 Firestore 每次将文档添加到此集合时生成一个新的文档 ID,方法是使用 add() 方法。

    大致如下:

    const messagesCollection = firestore.collection("users").doc(uid).collection('messages');
    
    const messagePayload = {foo: 'bar', bar: 'foo'};
    messagesCollection.add({messagePayload});
    

    【讨论】:

    • 我也会尝试这样做。消息不会很多,可能是 1 或 2 条消息,或者最多少于 5 条消息
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多