我不知道何时向 Firebase Firestore 数据库添加或更新条目。
使用 doc_ref.set
如果文档不存在,将添加该文档。如果它已经存在并且 set 被调用,它还将覆盖所有文档字段。
使用 doc_ref.update
如果文档存在,将更新文档的字段。如果该文档不存在,则什么也不会发生。
如果该字段当前不存在,如何向文档添加新字段,或者如果该字段存在则更新该字段?我可以读取数据库并检查该字段是否存在,然后使用 set
或 update
,但肯定有更简单的方法吗?
最佳答案
您正在寻找的是 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/