Home > other >  How to unify this two instructions?
How to unify this two instructions?

Time:11-02

Is it possible to unify in a single instruction these two Firestore document set/update?

await batchArray[batchIndex].set(finref, doc2.data());
     
await batchArray[batchIndex].update(finref, {"esito" : 1, "timestamp": currentTime});

Where "finref" is a document reference and doc2 is a DocumentSnapshot

CodePudding user response:

You can merge those two objects using spread syntax and pass it to single command.

await batchArray[batchIndex].set(finref, {
  ...doc2.data(),
  ...{
    "esito": 1,
    "timestamp": currentTime
  }
});

CodePudding user response:

If you want to perform both operations at once, then you can execute multiple write operations as a single batch that contains any combination of set(), update(), or even delete() operations. A batch of writes completes atomically, meaning that all operations will succeed or all will fail.

As you can see in the docs, the first argument is always a document reference. If you already have a document snapshot, then you need to get the document reference out of that object in order to commit the batch.

Edit:

If you try to update a document, that doesn't exist, indeed you'll get an error that says "No document to update". In that case, you should consider using set() with merge: true. This means that, if the document does not exist, then it will be created, and if the document does exist, the data will be merged into the existing document.

  • Related