yN.
yN.

Reputation: 2257

Start a firestore transaction without a transaction.get()

I want to move a doc from one collection to another. Therefore I want to use a transaction to 1. create the new doc and 2. delete the old one.

I can do the following, which works:

db.runTransaction((transaction) => {
return transaction.get(docRef)
  .then(() => transaction.set(newDocRef.doc(docId), doc))
  .then(() => transaction.delete(docRef));

How can I rewrite this code to start with a transaction.set() instead of a transaction.get() since I already have the doc in this context so its redundant. The difference is that transaction.get() returns a promise whereas transaction.set() returns a transaction.

Upvotes: 6

Views: 3761

Answers (4)

LeadDreamer
LeadDreamer

Reputation: 3499

Wrap the "transaction.set" in a Promise:

db.runTransaction((transaction) => {
return Promise.resolve(transaction.set(newDocRef.doc(docId), doc))
  .then(() => transaction.delete(docRef));

Upvotes: 0

dRamentol
dRamentol

Reputation: 1060

I use transactions when I have persistence enabled and I want some document creation fail when there's no internet connection. This is how I do it:

let docRef = db.collection("my-collection").doc();
db.runTransaction(async transaction => transaction.set(docRef, { field: "value"}));

Upvotes: 0

ya379
ya379

Reputation: 81

Well if you do not want to read the document, you should be using Batched Writes.

Firestore Docs:https://firebase.google.com/docs/firestore/manage-data/transactions

Batched writes

If you do not need to read any documents in your operation set, you can execute multiple write operations as a single batch that contains any combination of set(), update(), or delete() operations. A batch of writes completes atomically and can write to multiple documents.

Upvotes: 4

Hua Mai
Hua Mai

Reputation: 109

I'm afraid you can't do that...

The transaction doc: https://firebase.google.com/docs/firestore/manage-data/transactions

When using transactions, note that:

  • Read operations must come before write operations.

  • A function calling a transaction (transaction function) might run more than once if a concurrent edit affects a document that the transaction reads.

  • Transaction functions should not directly modify application state.

  • Transactions will fail when the client is offline.

Upvotes: 1

Related Questions