JS3
JS3

Reputation: 1847

Is this the correct way for storing a sub-collection?

I have a users collection and from there I wanted to have a sub-collection about the vaccination info of the specific user. This is how I save the sub-collection inside the user's collections.

const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const userRef = firestore
        .collection("users")
        .doc(uid)
        .collection("vaccination")
        .doc();
      const ref = userRef.set(
        {
          vaccineType,
          firstDoseDate,
          secDoseDate,
          firstVaccinator,
          secondVaccinator,
        },
        { merge: true }
      );

      console.log(" saved");
    } catch (err) {
      console.log(err);
    }
  };

This is what it looks like in firestore: enter image description here

enter image description here

enter image description here

Upvotes: 0

Views: 29

Answers (1)

I'm Joe Too
I'm Joe Too

Reputation: 5870

This is the correct way to create a subcollection, but note that you do not need the merge option here. merge is used when you are updating an existing document and don't want to fully overwrite it. In your case, you're not passing an existing subcollection doc id so set will create a new document and there's nothing to merge.

You also need to await the set function as it returns a promise that you need to await for it to resolve.

// This creates a new document and you don't need {merge: true}
const newDocRef = firestore
  .collection("users")
  .doc(uid)
  .collection("vaccination")
  .doc();
const newDoc = await newDocRef.set({
  vaccineType,
  firstDoseDate,
  secDoseDate,
  firstVaccinator,
  secondVaccinator,
});

// This updates an existing document, in which case you might want
// {merge: true} if you don't want to overwrite the entire document
// but just want to write/update the fields in the set call.
const existingDocRef = firestore
  .collection("users")
  .doc(uid)
  .collection("vaccination")
  .doc(vaccinationDocId);
const updatedExistingDoc = await existingDocRef.set({
  vaccineType,
  firstDoseDate,
  secDoseDate,
  firstVaccinator,
  secondVaccinator,
}, { merge: true });

Upvotes: 1

Related Questions