【问题标题】:React and Firebase database - how to make multiple simultaneously updateReact 和 Firebase 数据库 - 如何使多个同时更新
【发布时间】:2017-04-30 11:32:49
【问题描述】:

我正在尝试通过多个同时更新来更新 Firebase 数据库。但我收到了Firebase.update failed: First argument contains a path that is ancestor of another path

我更新数据库的代码如下所示:

onGoalAdd = (name, description, startDate, finishDate, remark, main) => {

    var newGoalData = {
      name: name,
      description: description,
      startDate: startDate,
      finishDate: finishDate,
      remark: remark,
      main: main,
    };

    var mainGoalData = {
      main: ""
    }

    let myRefKey = dbRef.child('/goals/'+this.state.uid).push().key;

    var updates = {};
    updates['/goals/'+this.state.uid+'/'+myRefKey] = newGoalData;
    updates['/goals/'+this.state.uid] = mainGoalData;

    dbRef.update(updates);

    this.setState({
      goalKey: myRefKey,
    });
  }

期望的结果是使用uid/myRefKey 下的所有newGoalData 更新数据库,同时在uid 下添加空的主属性。

请问正确的方法是什么?

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    所以这解决了我的情况:

      componentDidMount = () => {
        const dataGoalRef = dbRef.child('goals/'+this.state.uid);
        const mainGoalRef = dbRef.child('goals/'+this.state.uid);
      }
    
      onGoalAdd = (name, description, startDate, finishDate, remark, main) => {
        let myRefKey = dbRef.child('goals/'+this.state.uid).push().key;
        this.dataGoalRef = dbRef.child('goals/'+this.state.uid+'/'+myRefKey);
        this.mainGoalRef = dbRef.child('goals/'+this.state.uid);
    
        this.dataGoalRef.update({
          name: name,
          description: description,
          startDate: startDate,
          finishDate: finishDate,
          remark: remark,
        });
    
        this.mainGoalRef.update({
          mainGoal: ""
        });
        this.setState({
          goalKey: myRefKey,
        });
      }
    

    请问有什么更好的办法吗?

    【讨论】:

      【解决方案2】:

      我遇到了类似的错误。 解决方法是在更新对象的路径末尾附加适当的对象键,并逐个键构建更新对象。

      所以在目前的情况下,这样的事情应该可以工作:

      ...
      const updates = {};
      
      for (const key in newGoalData) {
        updates[`/goals/${this.state.uid}/${myRefKey}/${key}`] = newGoalData[key];
      }
      
      for (const key in mainGoalData) {    // assuming that mainGoalData has multiple keys
        updates[`/goals/${this.state.uid}/${key}`] = mainGoalData[key];
      }
      
      dbRef.update(updates, error => {...some optional code...});
      
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-19
        • 1970-01-01
        • 2020-03-10
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多