Firebase Cloud Firestore创建条目或更新(如果已存在) [英] Firebase Cloud Firestore create entry or update if it already exists
问题描述
我有个问题,知道何时向Firebase Firestore数据库添加或更新条目.
I have an issue of knowing when to add or update an entry to a Firebase Firestore database.
使用doc_ref.set
将添加一个文档(如果该文档不存在).如果已经存在并调用set,它将覆盖所有文档字段.
Using doc_ref.set
will add a document if it does not exist. It will also override all of a documents fields if it already exists and set is called.
如果文档存在,使用doc_ref.update
将更新文档的字段.如果该文档不存在,则什么也不会发生.
Using doc_ref.update
will update fields of a document if the document exists. If the document does not exist, nothing happens.
如果该字段当前不存在,如何将新字段添加到文档中;如果该字段存在,则如何更新该字段?我可以读取数据库并检查该字段是否存在,然后使用set
或update
,但是肯定有更简单的方法吗?
How do I add a new field to a document if the field does not currently exist, or update the field if it does exist? I could read the database and check if the field exists, and then use either set
or update
, but surely there is an easier way?
推荐答案
您要查找的是set
操作中的merge
选项.从设置文档上的文档:>
What you're looking for is the merge
option in the set
operation. From the documentation on 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创建条目或更新(如果已存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!