问题
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