React和Firebase数据库 - 如何使多个同时更新

时间:2017-04-30 11:32:49

标签: javascript reactjs firebase firebase-realtime-database

我正在尝试使用多个同时更新来更新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,
    });
  }

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

请问正确的方法是什么?

2 个答案:

答案 0 :(得分:0)

所以这解决了我的情况:

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

请问有更好的解决方案吗?

答案 1 :(得分:0)

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

因此,在目前情况下,类似这样的方法应该起作用:

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

...