Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple document reads in node js Firestore transaction

I want to perform a transaction that requires updating two documents using the previous values of those documents.

For the sake of the question, I'm trying to transfer 100 tokens from one app user to another. This operation must be atomic to keep the data integrity of my DB, so on the server side I though to use admin.firestore().runTransaction.

As I understand runTransaction needs to perform all reads before performing writes, so how do I read both user's balance before updating the data?

This is what I have so far:

db = admin.firestore();
const user1Ref = db.collection('users').doc(user1Id);
const user2Ref = db.collection('users').doc(user2Id);
transaction = db.runTransaction(t => {
    return t.get(user1Ref).then(user1Snap => {
        const user1Balance = user1Snap.data().balance;
        // Somehow get the second user's balance (user2Balance)
        t.update(user1Ref , {balance: user1Balance - 100});
        t.update(user2Ref , {balance: user2Balance + 100});
        return Promise.resolve('Transferred 100 tokens from ' + user1Id + ' to ' + user2Id);
    });
}).then(result => {
    console.log('Transaction success', result);
});
like image 599
Dori Avatar asked May 15 '18 12:05

Dori


1 Answers

You can use getAll. See documentation at https://cloud.google.com/nodejs/docs/reference/firestore/0.15.x/Transaction?authuser=0#getAll

like image 176
Derrick Miller Avatar answered Oct 03 '22 04:10

Derrick Miller