簡體   English   中英

如何保存多條消息並將其保存在 firestore 的不同字段中?

[英]How can I save multiple messages and save it in separate fields in firestore?

這是某個用戶的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中保存一條消息並保存另一條消息而不影響上一條消息?

我了解您正在覆蓋users集合中的同一文檔。 這可能是(我們沒有看到整個代碼)因為您沒有在兩次寫入之間更改uid的值。 uid是文檔 ID,它會被覆蓋(即使您使用{ merge: true }選項,如果msg對象包含現有字段,它們也會被覆蓋)。

您提到您保存消息,所以我猜您想為給定用戶(該用戶由uid標識)保存幾條消息。 因此,您可以在用戶的​​文檔下創建一個子集合,並在每次向該集合添加文檔時讓 Firestore 使用add()方法生成一個新的文檔 ID。

大致如下:

const messagesCollection = firestore.collection("users").doc(uid).collection('messages');

const messagePayload = {foo: 'bar', bar: 'foo'};
messagesCollection.add({messagePayload});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM