【问题标题】:How to add a map in array in firebase firestore in react?如何在firebase firestore的数组中添加地图以做出反应?
【发布时间】:2020-11-01 14:30:24
【问题描述】:
  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"
                              >

在这里,在上面的代码中,我尝试在数组中添加更多地图,用于特定的文档 ID。因此,在按钮提交时,我将使用“addMoreCases”功能。它还应该在casesObject 数组的caseAndAssociatesData 字段中添加另一个映射。我将附上我的firestore数据库图像,在“casesAndAssociatesData”字段中,在“casesObject”数组中,我需要另一个带有表单值的映射,应该添加递增的Indexin 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"

【问题讨论】:

    标签: javascript arrays reactjs firebase google-cloud-firestore


    【解决方案1】:

    据我了解,您的数据库中有以下结构:

    collection:
     document:
        casesAndAssociatesData:obj_array
        casesObject:obj_array
    

    您想向casesObject 添加更多数据。由于 casesObject 是文档的一个字段,因此每次添加更多数据时都必须更新它。

    所以方法是:

    1. 从加载的文档中获取所有数据作为地图数组。
    2. 向该数组添加另一个元素。
    3. 使用新数据更新整个 casesObject 字段。

    这是如何修改代码的示例:

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

    我已经在我的数据库上对此进行了测试,它的工作方式与您描述的一样。每次添加新的地图数据时,它只更新字段casesObject

    【讨论】:

    • 尊敬的先生,谢谢。以及如何更新该地图中的特定字段?
    • 您可以使用dot notation 这样做。请参阅 Cloud Firestore Firebase 中的Update fields in nested objects 文档。
    • 尊敬的先生,我这样做了...但我收到错误为“未处理的拒绝(FirebaseError):使用无效数据调用的函数 DocumentReference.update()。不支持嵌套数组”跨度>
    • 我还用具有数据库结构的图像更新了问题
    • 您好,我刚刚尝试了您的解决方案,以更新我在数据库中的值,但我收到此错误调用 documentupdate 时抛出不支持嵌套数组您能回复吗?
    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2015-11-05
    • 2017-09-29
    • 2020-08-27
    相关资源
    最近更新 更多