Home > database >  Firestore cloud function add field to document
Firestore cloud function add field to document

Time:11-25

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?

CodePudding user response:

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);
    });
  //});
}

CodePudding user response:

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.

  • Related