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
2
Answers
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 evendelete()
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()
withmerge: 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.You can merge those two objects using spread syntax and pass it to single command.