Home > Enterprise >  Firestore - Skip document update if it doesn't exists, without need of failures
Firestore - Skip document update if it doesn't exists, without need of failures

Time:05-16

I have a collection

/userFeed 

Where I create/delete docs (representing users) when the current user starts following/unfollowing them.

...
  /userFeed (C)
    /some-followed-user (D)
      -date <timestamp>
      -interactions <number>

When the user likes a post, the interactions field will be updated. But... what if the user doesn't follow the post owner? Then, I will just need to skip the document update, without necessity of producing failures/errors.

const currentUserFeedRef = firestore
    .collection("feeds")
    .doc(currentUserId)
    .collection("userFeed")
    .doc(otherUserId);

  const data = {
    totalInteractions: admin.firestore.FieldValue.increment(value),
  };

  const precondition = {
    exists: false, // I am trying weird things
  };

  if (batchOrTransaction) {
    return batchOrTransaction.update(
      currentUserFeedRef,
      data,
      precondition
    );
  } 

Is it possible to just "skip the update if the doc doesn't exist"?

CodePudding user response:

Is it possible to just "skip the update if the doc doesn't exist"?

No, not in the way that you're explaining it. Firestore updates don't silently fail.

If you need to know if a document exists before updating it, you should simply read it first and check that it exists. You can do this very easily in a transaction, and you can be sure that the update won't fail due to the document being missing if you check it this way first using the transaction object.

In fact, what you are trying to do is illustrated as the very first example in the documentation.

  • Related