在firebase文档之后,.update仍将被覆盖

时间:2018-07-13 14:38:42

标签: javascript firebase firebase-realtime-database

我正在遵循this guidethis reference document尝试更新具有键/值的节点,其中键是在其他位置生成的pushID。我已经尝试了几种不同的方法,并且它总是会覆盖任何现有的pushID键,但不会与同一父级上的其他非pushID键/值对混淆。关于我在做什么错的任何想法吗?我还要注意,这是在firebase云功能中运行的-这是代码

这是我尝试过的代码:

const parentNode = "zzABCDEFG" //this is an internal reference that I must use

const parentNodeRef = admin.database().ref().child(parentNode)

const PushIDSnap = await admin.database().ref('/ref/to/another/pushID/elsewhere').once('value')

const PushIDSnapVal = PushIDSnap.val() //getting the pushID that I want to set as the key

await parentNodeRef.child(PushIDSnapVal).set(Data)

我也尝试过:

const obj = {}

obj[PushIDSnapVal] = Data

console.log(obj) //console in firebase cloud-functions correctly shows { '-LH9-nBF6Wx3g6oSq154': '-LHBg3xKC51qYG6WAq65*FL' }

await parentNodeRef.update(obj) //this does the same thing--overwrites any existing AND DIFFERENT pushID's that are children of the parentNode

也尝试过,类似于上述内容,但使用完整路径-与其他两个路径相同

const obj = {}

const key = '/' + parentNode + '/' + PushIDSnapVal

obj[key] = Data

console.log(obj) //console in firebase cloud-functions correctly shows { '/ACGDIQCZZ/-LH9-nBF6Wx3g6oSq154': '-LHBg3xKC51qYG6WAq65*FL' }

await admin.database().ref().update(obj) //this does the same thing--overwrites any existing AND DIFFERENT pushID's that are children of the parentNode

这是我得到的JSON树(直接从firebase控制台的导出文件中复制):

"zzACGAFCG" : {

    "-LHA_9g4U8GzpjxiJmpa" : "-LHGXaRWxHhpWHeGk5Ob^MB", 

    "tT" : "D"

}, 

当我使用不同的pushID再次运行它时,它只会覆盖第一个键/值对,并且不会弄乱'tT'子节点

这就是我想要的:

"zzACGAFCG" : {

    "-LHA_9g4U8GzpjxiJmpa" : "-LHGXaRWxHhpWHeGk5Ob^MB", 

    "-LH9-nBF6Wx3g6oSq154" : "-LHFN0BZ2FNWUExOnulR^NA",

    "tT" : "D"

},

当我使用其他pushID再次运行它时,应添加新的键/值对并保留旧的键/值对。

1 个答案:

答案 0 :(得分:1)

要从需要的内容中获得所需的东西,您需要运行此更新:

var ref = firebase.database.ref("zzACGAFCG");
ref.update({ "-LH9-nBF6Wx3g6oSq154": "-LHFN0BZ2FNWUExOnulR^NA" });

这是最小的,所以我认为您需要在代码中做更多的工作才能到达这里。我将在下面为您提供一些有关多位置更新如何工作的背景信息。


要意识到的最重要的事情是,一条update语句循环遍历您提供的对象中的所有键/路径,并且实际上对每个键/路径执行set操作。

假设您具有以下JSON:

{
  "root": {
    "messages": {
      "message1": "blablabla",
      "message2": "blablabla"
    }
  }
}

如果运行此更新语句:

var root = firebase.database().ref("root");
root.update({ messages: { message3: "new message" } });

然后整个/root/messages节点将被更新替换,因此结果将是:

{
  "root": {
    "messages": {
      "message3": "new message"
    }
  }
}

正如我所说,除了更新对象中第一级键/路径之外,数据库还执行set()操作。它不会进行深度合并。

如果要修补较低级别的节点,则需要确保在更新对象的键中具有要更新的属性的完整路径。所以:

root.update({ "messages/message3": "new message" });

将导致:

{
  "root": {
    "messages": {
      "message1": "blablabla",
      "message2": "blablabla",
      "message3": "new message"
    }
  }
}