简体   繁体   中英

Firebase firestore data inconsistency

I'm developing a project which consists of a "following" and "unfollowing" feature just like a social media app. Each time a user follows or unfollows four different actions are run for both the functionality.
Let's say, for the following feature , I have the below code,

export const followUser = async (profile)=>{
  try{
     await db.collection('_').doc('_').set({...});       //line 1
     await db.collection('_').doc('_').set({...});       //line 2
     await db.collection('_').doc('_').update({...});    //line 3
     await db.collection('_').doc('_').update({...});    //line 4
  }
  catch(error){
     throw error;
  }
}   

I found out that there could be data inconsistency as for some reason if line3 fails it will go into the catch block but line1 and line2 have already been executed causing inconsistency.
Is there a way in which if any of the four actions fails I can move to catch block without any single action been executed.

What you need in this case are firestore batch writes which ensure atomicity across writes, so either all your writes fail or all of them are successful leaving no data inconsistencies behind.

So you can do something like:

const batch = db.batch();

batch.set(ref, {...});
batch.set(ref, {...});
batch.update(ref, {...});
batch.update(ref, {...});

await batch.commit();

Please note that a single batch can contain up to 500 write operations (set, update and deletes operations).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM