Home > Software design >  Best practice for adding a history subcollection upon submitting the form without cloud functions
Best practice for adding a history subcollection upon submitting the form without cloud functions

Time:02-28

I have this form to submit the products. Also, I want to store the date of when it was submitted along with the data in the subcollection history. So, this is what I did:

When adding a product and storing the history of it as well

const handleSubmit = async (e) => {
    e.preventDefault();

    const docRef = await addDoc(collection(db, "products"), {
      productName,
      Number(price),
      size,
      cat,
      colorMap,
    });

    const historyRef = await doc(db, "products", docRef.id);
    const colRef = collection(historyRef, "history");
    addDoc(colRef, {
      productName,
      Number(price),
      size,
      cat,
      colorMap,
      createdDate: new Date(),
    });

    setOpen(true);
    console.log("Document written with ID: ", docRef.id);
  };

This is how I save it in Firebase:

enter image description here

I also have another form that in editing a product that will store the changes that we made in another document inside the history subcollection.

The way that I've added the subcollection upon submission, is this alright or would it cause complications in the future? Or should I make a function to call this or are there any other suggestions? Thank you. Any help would be appreciated.

CodePudding user response:

From your question it is clear that your Firestore Database Structure is like the following -

Collection - products

    Document 1
        
        Subcollection - history
            
            History document 1
            History document 2
            ………
    Document 2
        
        Subcollection - history
            
            History document 1
            History document 2
            ………
    Document 3
        
        Subcollection - history
            
            History document 1
            History document 2
            ………

It seems to be fine. But in future, if there are many edits made for a product, then there will be a lot of documents inside the history subcollection, which may seem redundant. So you may consider deleting the documents inside the history subcollection based on your need. For example, you may consider deleting the history which is 6 months old.

You may go through this document to know some best practices while structuring your Firestore database.

  • Related