Home > Enterprise >  How can I save multiple messages and save it in separate fields in firestore?
How can I save multiple messages and save it in separate fields in firestore?

Time:11-19

This is the firestore document of a certain user:

enter image description here

This is how I'll save messages to be saved in 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>
  );
};

In this way, I can save the message in the firestore, however, if I'll send another one, it will replace the previous message saved in it. How can I save a message in firestore and save another message without it affecting the previous message?

CodePudding user response:

I understand that you are overriding the same document in the users collection. This is probably (we don't see the entire code) because you don't change the value of uid between the two writes. uid being the Document ID, it is overwritten (even if you use the { merge: true } option, if the msg object contains existing fields, they are overwritten).

You mention that you save messages, so I guess you want to save several messages for a given user (this user being identified by uid). So you could have a subcollection under the user's document and let Firestore generates a new Document ID each time you add a document to this collection, by using the add() method.

Something along the following lines:

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

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