E. Williams
E. Williams

Reputation: 425

Save a copy of a field before updating it on Firestore

I have the following document structure:

currencies[
    {
        value: 0.00012,
        last: 0.00013
    },
...]

I am using an external service to get the new rates of each currency. But before updating value I want to move its value to last field so I have a "backup" of the last value before the updates.

What I have done so far is updating value field succesfuly. But I don't have any idea of how to move value to last before updating in the same transaction.

db.collection("currencies")
            .doc('USD')
            .set({ value: newRates['USD'] })
            .catch((error) => {
              console.log(error);
            });

Upvotes: 0

Views: 35

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50920

You would have to read the existing value and then update it back in the last field. There isn't any method to do this in single go.

const docRef = db.collection("currencies").doc('USD')

const curValue = (await docRef.get()).data().value

await docRef.update({value: "newValue", last: curValue})

Upvotes: 1

Related Questions