Firebase Cloud Firestore 创建条目或更新(如果已存在)

标签 firebase google-cloud-firestore

我不知道何时向 Firebase Firestore 数据库添加或更新条目。

使用 doc_ref.set如果文档不存在,将添加该文档。如果它已经存在并且 set 被调用,它还将覆盖所有文档字段。

使用 doc_ref.update如果文档存在,将更新文档的字段。如果该文档不存在,则什么也不会发生。

如果该字段当前不存在,如何向文档添加新字段,或者如果该字段存在则更新该字段?我可以读取数据库并检查该字段是否存在,然后使用 setupdate ,但肯定有更简单的方法吗?

最佳答案

您正在寻找的是 merge set 中的选项手术。来自 setting a document 上的文档:

var cityRef = db.collection('cities').doc('BJ');

var setWithMerge = cityRef.set({
    capital: true
}, { merge: true });

If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.

关于Firebase Cloud Firestore 创建条目或更新(如果已存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452688/

相关文章:

ios - 在iOS中配置多个scheme会导致风格不匹配

ios - 将图像 URL 从 firebase 存储存储到数据库是否安全?

firebase - Flutter 检查用户名是否已存在于 Firestore 数据库中

ios - SwiftUI Firestore 数据在第一次加载时不显示

java - 如何在自定义对象类中设置 @ServerTimestamp 注释 - Firestore

android - Flutter 和 android studio 错误 : Google Play Store is missing

ios - Firebase 与模拟器连接但不在真实设备 iOS 中

javascript - firebase "Uncaught TypeError: undefined is not a function"错误

firebase - 部署时使 Google Cloud Function 的 Firebase 缓存无效

java - 无法更新 Firebase Java 中的完整子对象