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

152
Views
Firestore cloud function add field to document

Im trying to write a cloud function that lets me create a collection with a document and than adds field to that document. currently my function creates the collection and comment but oreplaces each field every time and overwrites the existing one, so after all the data is pushed i only end up with one field. How do i go about adding a field each time? my code

if (data && typeof data === "object") {
   Object.keys(data).forEach((docKey) => {
  firestore
    .collection(collectionKey)
    .doc("quotes")
    .set(data[docKey])
    .then((res) => {
      console.log("Document successfully written!");
    })
    .catch((error) => {
      console.error("Error writing document: ", error);
    });
  //});
}

data

"2": {
    "Quote": "Lorem Ipsum"
  },
  "3": {
    "Quote": "123"
  },
  "4": {
    "Quote": "456"
  }

after i run the function the only thing that will be in the document quotes is the last entry "456". How do i go about all the fields staying?

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

0

It seems you are trying to update the doc but you are using the .set() function which updates your document with newly provided data. You will need .update() instead to keep your previous data.

if (data && typeof data === "object") {
   Object.keys(data).forEach((docKey) => {
  firestore
    .collection(collectionKey)
    .doc("quotes")
    .update(data[docKey])
    .then((res) => {
      console.log("Document successfully written!");
    })
    .catch((error) => {
      console.error("Error writing document: ", error);
    });
  //});
}
about 4 years ago · Juan Pablo Isaza Report

0

To add fields to an existing document, use update as Anuj's answer shows.

If you want to both create the initial document and update it with a single statement, you can pass the merge: true option to set():

firestore
  .collection(collectionKey)
  .doc("quotes")
  .set({ [docKey]: data[docKey] }, { merge: true })

You'll note I also added [docKey]: to the data, as I expect you want the value of docKey to become the field name.

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!