Home > Software design >  How do I save this in firestore the way I want it to be to be structured?
How do I save this in firestore the way I want it to be to be structured?

Time:03-02

I have these data:

orders = {
  firstName: "Jennie",
  lastName: "asdasda",
  address: "US",
  order: [
    { product: "Tumbler - 500- ML ", variation: [{ qty: 12, color: "red" }] },
    { product: "Shirt - M ", variation: [{ qty: 14, color: "green" }] }
  ],
  instructions: "asdasdad",
  contact: "182738123"
};

Saving this in firestore would look like this:

enter image description here

How do I save this in firestore where the fields of firstName, lastName, address, contact and instructions is not inside the orders map?

I kind of wanted to save it like this:

enter image description here

This is how I saved it in Firestore:

 const Save = () => {
      const { state } = useStateMachine(updateAction);
      const orders = state.yourDetails;
    
      const handleAdd = async () => {
        try {
          const docRef = await addDoc(collection(db, "orders"), { orders });
          console.log("Document written with ID: ", docRef.id);
        } catch (err) {
          console.log(err);
        }
      };
    
      return (
        <div>
          Results
          <pre>{JSON.stringify(state.yourDetails, null, 2)}</pre>
          <button onClick={handleAdd}>Add </button>
        </div>
      );
    };
    
    export default Save;

CodePudding user response:

remove the curly bracket from { orders }:

 const Save = () => {
      const { state } = useStateMachine(updateAction);
      const orders = state.yourDetails;
    
      const handleAdd = async () => {
        try {
          const docRef = await addDoc(collection(db, "orders"), orders);
          console.log("Document written with ID: ", docRef.id);
        } catch (err) {
          console.log(err);
        }
      };
    
      return (
        <div>
          Results
          <pre>{JSON.stringify(state.yourDetails, null, 2)}</pre>
          <button onClick={handleAdd}>Add </button>
        </div>
      );
    };
    
    export default Save;
  • Related