Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
How can I save multiple messages and save it in separate fields in firestore?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!