3
votes

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?

2

2 Answers

5
votes

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.

0
votes

I had similar problem, but I wanted to update array field using FieldValue.arrayUnion, FieldValue.arrayRemove. Therefore could not use set/merge.

To avoid checking if document exists before update (costs 1 read), I wrapped update statement with try/catch and check for error code 5 (NOT FOUND). In this case, set value instead of update. Code example:

  try {
    await docRef.update({
      arrayField: admin.firestore.FieldValue.arrayUnion(...dates),
    });
  } catch (error) {
    if (error.code === 5) {
      // Error: 5 NOT_FOUND: no entity to update:
      await docRef.set({
        arrayField: dates,
      });
    }
  }