在父节点Firebase RealTime中更新值时如何推送到子节点

时间:2020-08-04 22:46:46

标签: javascript reactjs firebase firebase-realtime-database

我正在尝试更新Firebase实时数据库的父节点中的值,同时将数据推送到子节点,但是出现错误“ Reference.update失败:第一个参数包含/ xyz的祖先路径另一个路径/ xyz /.../..."

const updatedPosition = {
            category: values.category,
            shares: newShares,
            cost: newCost,
        }

let updates = {}
const newTransactionKey = docRef.child('transactions').push().key;
updates[ticker + '/transactions/' + newTransactionKey] ={
                        date: new Date().toString(),
                        transaction: `${Number(values.shares)} shares added @ $${perShare} ea`
                    }
updates[ticker] = updatedPosition;
let updateSuccess = true;
await docRef.update(updates, (error) => {
    console.log(error);
    if (error){
        updateSuccess = false;
       }
});

我的数据的结构如下:

parentNode: {
    category: "string",
    shares: "number",
    cost: "number",
    transactions: {
        0:{
            date: DateString,
            type: "string"
          }
    }
}

1 个答案:

答案 0 :(得分:0)

您的updates包含以下两个键:

${ticker}/transactions/${newTransactionKey}
${ticker}

这有助于认识到实时数据库将多位置更新作为set语句的列表进行处理。因此,第一行将值设置为${ticker}下的深键,然后第二行将值设置为${ticker}

这意味着第二个键将完全覆盖第一个键。既然总是这样,那是一个编程错误,数据库拒绝了它。

如果您也想在更新下更新categorysharescost,则需要分别添加它们:

let updates = {}
const newTransactionKey = docRef.child('transactions').push().key;
updates[`${ticker}/transactions/${newTransactionKey}`] ={
    date: new Date().toString(),
    transaction: `${Number(values.shares)} shares added @ $${perShare} ea`
}
updates[`${ticker}/category`] = values.category;
updates[`${ticker}/shares`] = newShares;
updates[`${ticker}/cost`] = newCost;

现在${ticker}下有4个单独的更新,并且没有一个与另一个重叠。