Firebase Cloud Firestore create entry or update if it already exists

喜夏-厌秋 提交于 2020-05-09 06:51:06

问题


I have an issue of knowing when to add or update an entry to a Firebase Firestore database.

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.

Using doc_ref.update will update fields of a document if the document exists. If the document does not exist, nothing happens.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/58452688/firebase-cloud-firestore-create-entry-or-update-if-it-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!