firebase - Firestore 使用动态键更新嵌套对象中的字段

标签 firebase cloud google-cloud-firestore

我需要使用动态键更新嵌套对象中的字段。
路径可能如下所示: level1.level2.DYNAMIC_KEY : updatedValue
update-method 删除 level1 上的所有其他内容,而不是仅更新嵌套对象中的字段。 update() 的作用更像是 set()。我究竟做错了什么?

我已经尝试了以下方法:

我阅读了文档 https://firebase.google.com/docs/firestore/manage-data/add-data#update-data
但那样它是 a) 静态和 b) 仍然删除其他字段。

Update fields in nested objects If your document contains nested objects, you can use "dot notation" to reference nested fields within the document when you call update()



这将是静态的并导致
update({
'level1.level2.STATIC_KEY' : 'updatedValue'
});

然后我找到了这个答案 https://stackoverflow.com/a/47296152/5552695
这帮助我使更新路径动态化。
在此之后所需的解决方案可能看起来像
field[`level1.level2.${DYNAMIC_KEY}`] = updateValue;
update(field);

但仍然:它会删除此路径中的其他字段。

更新:

我的文档结构如下:
Snapshot

所以在这个结构中我只想更新 complexArray > 0 > innerObject > 年龄

将上述路径写入 update() 方法将删除 complexArray 级别上的所有其他内容。
对一级字段的简单更新工作正常,并让其他一级字段保持不变。

是否有可能像 update() 这样的 Firestore 函数只能作用于文档的最低字段级别。一旦我将复杂的对象放入文档中,就不可能选择这样的内部字段?
我知道会有解决方案将这些“复杂”对象提取到单独的集合 + 文档中,并将它们放入我当前的最低文档级别。我认为这将是坚持 FireStore 原则的更准确方法。但是在应用程序方面,处理复杂对象比总是深入研究 firestore 集合 + 文档结构更容易。

所以我当前的解决方案是将整个复杂对象发送到 update() 方法中,即使我只更改了应用程序端的一个字段。

最佳答案

您是否尝试过使用 { merge: true }您的请求中的选项?

db
  .collection("myCollection")
  .doc("myDoc")
  .set(
    { 
      level1: { level2: { myField: "myValue" } }
    },
    { merge: true }
  )

关于firebase - Firestore 使用动态键更新嵌套对象中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665752/

相关文章:

xcode - iOS 16 + 火力地堡 : The app references non-public selectors determineAppInstallationAttributionWithCompletionHandler:

azure - 创建 Azure Api 管理时 Vnet 未列出

firebase - 如何在 Cloud Firestore 中使用 Stream 回调

android - 将 Firebase 任务<Void> 包装到 RxJava CompletableEmitter 中?

Microsoft Azure 订阅下的 Windows Server 2012 R2 远程桌面许可证激活

kubernetes - 从 EOF metric-server kubernetes 获取 TLS 握手错误

javascript - 如何将数据从用户注册表单发送到 firebase 数据库

Firebase onDisconnect 现在不是 100% 可靠吗?

javascript - Firebase 在 React Native 数据获取中返回 "undefined"值

c# - RavenDB 搜索多个单词