简体   繁体   中英

How to add a map in array in firebase firestore in react?

  addMoreCases = (e) => {
    e.preventDefault();
    this.setState({
      makeActive10: false,
      toggleDetails10: true,
    });
    const studentName = this.props.location.state.selectedStudent.basicData
      .studentName;
    var db = fire.firestore();
    const casesObject = this.state.casesObject;
    db.collection("students")
      .where("basicData.studentName", "==", studentName)
      .get()
      .then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
          console.log(doc.id, " => ", doc.data());
          db.collection("students")
            .doc(doc.id)
            // .doc(  )
            .update(
              {
                ...{
                  casesAndAssociatesData: {
                    ...{ casesObject },
                  },
                },
              }

              // { merge: true }
            );
        });
      });
    this.setState({
      casesObject: [
        // { ...initialCasesForm }
        {
          casesPoliceStation: "",
          crimeNumber: "",
          sectionOfLaw: "",
          stage: "",
        },
      ],
    });
  };
                        <Form onSubmit={this.addMoreCases}>
                          <Form.Row key={index}>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="casesPoliceStation"
                                placeholder="Police Station"
                                value={cases.casesPoliceStation}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="crimeNumber"
                                placeholder="Crime Number"
                                value={cases.crimeNumber}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="sectionOfLaw"
                                placeholder="Section Of Law"
                                value={cases.sectionOfLaw}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="stage"
                                placeholder="Stage"
                                value={cases.stage}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Button
                                type="submit"
                                variant="outline-primary"
                              >

Here, in the above code I'm trying to add some more maps in an array using for the specific document ID. So that on button submit, I'm alling function "addMoreCases". And it sould add another map within casesObject array, within casesAndAssociatesData field. I'll be attaching my firestore database image, and in that, within "casesAndAssociatesData" field, within "casesObject" array, I need another map with the form values should be added with the incremented Index in the above image, if I enter the values in form and hit submit button, I need the values to be added in "casesObject" array with index "2" in "casasAndAssociatesData"

这是我的数据库结构 As far as I understand you have the following structure in your database:

collection:
 document:
    casesAndAssociatesData:obj_array
    casesObject:obj_array

And you would like to add more data to the casesObject . Since casesObject is a filed of the document, you will have to update it every time you add more data.

So the approach would be:

  1. Get all the data from the loaded document as an map array.
  2. Add another element to that array.
  3. Update the entire casesObject field with the new data.

This is an example of how you should modify your code:

querySnapshot.forEach(function (doc) {

   console.log(doc.id, " => ", doc.data());

   //Prepare the new data that you want to add :
   var newCasesObject = {
       casesPoliceStation: "New police station Value",
       crimeNumber: "New crime value",
       sectionOfLaw: "New section of law",
       stage: "ss",
   }

   //Get the array with data from the loaded document
   var dataObj = doc.data().casesObject;

   //Push the new data to that array
   dataObj.push(newCasesObject);

   //Call another function that will update the document with the new data
   updateData(doc.id, dataObj);

});

//The new update function:
async function updateData(docID, obj){

   const cityRef = db.collection('[COLLECTION_NAME]').doc(docID);

   // Set the 'capital' field of the city
   const res = await cityRef.update({casesObject: obj});

}

I have tested this on my database and it is working as you described. It updates only the field casesObject while every time adding a new map data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM