Cloud Firestore, डेटा को पढ़ने और लिखने के लिए ऐटॉमिक ऑपरेशन के साथ काम करता है. ऐटॉमिक संक्रियाओं के एक सेट में, या तो सभी संक्रियाएं सफल रहती हैं या कोई भी प्रक्रिया लागू नहीं होती. Cloud Firestore में दो तरह के ऐटॉमिक ऑपरेशन होते हैं:
- ट्रांज़ैक्शन: ट्रांज़ैक्शन एक या एक से ज़्यादा दस्तावेज़ों पर, पढ़ने और लिखने से जुड़ी कार्रवाइयों का सेट होता है.
- बैच किए गए राइट: बैच किए गए राइट, एक या एक से ज़्यादा दस्तावेज़ों पर लिखने के लिए कार्रवाइयों का सेट है.
लेन-देन की जानकारी के साथ डेटा अपडेट करना
Cloud Firestore क्लाइंट लाइब्रेरी का इस्तेमाल करके, कई कार्रवाइयों को एक ट्रांज़ैक्शन में ग्रुप किया जा सकता है. ट्रांज़ैक्शन तब काम आते हैं, जब आपको किसी फ़ील्ड की मौजूदा वैल्यू या किसी अन्य फ़ील्ड की वैल्यू के आधार पर वैल्यू अपडेट करनी हो.
लेन-देन में get()
ऑपरेशन की संख्या और उसके बाद set()
, update()
या delete()
जैसी राइट ऑपरेशन शामिल होती हैं. एक साथ बदलाव करने के मामले में, Cloud Firestore पूरे लेन-देन को फिर से चलाता है. उदाहरण के लिए, अगर
कोई लेन-देन दस्तावेज़ों को पढ़ता है और दूसरा क्लाइंट उनमें से किसी भी दस्तावेज़ में बदलाव करता है,
तो Cloud Firestore लेन-देन की फिर से कोशिश करेगा. इस सुविधा से यह पक्का होता है कि लेन-देन अप-टू-डेट और एक जैसे डेटा पर चलता रहे.
लेन-देन पर कभी भी आंशिक रूप से लिखना लागू नहीं होता है. सभी राइटिंग, लेन-देन के पूरा होने पर लागू होते हैं.
लेन-देन का इस्तेमाल करते समय, इन बातों पर ध्यान दें:
- ऑपरेशन लिखने से पहले रीड ऑपरेशन आने चाहिए.
- अगर एक ही समय में किए जाने वाले बदलाव की वजह से लेन-देन पढ़े जाने वाले दस्तावेज़ पर असर पड़ता है, तो लेन-देन (लेन-देन फ़ंक्शन) को कॉल करने वाला फ़ंक्शन एक से ज़्यादा बार चल सकता है.
- लेन-देन फ़ंक्शन को ऐप्लिकेशन की स्थिति में सीधे तौर पर बदलाव नहीं करना चाहिए.
- क्लाइंट के ऑफ़लाइन होने पर लेन-देन नहीं हो पाएंगे.
नीचे दिए गए उदाहरण में, ट्रांज़ैक्शन बनाने और उसे चलाने का तरीका बताया गया है:
Web
import { runTransaction } from "firebase/firestore"; try { await runTransaction(db, async (transaction) => { const sfDoc = await transaction.get(sfDocRef); if (!sfDoc.exists()) { throw "Document does not exist!"; } const newPopulation = sfDoc.data().population + 1; transaction.update(sfDocRef, { population: newPopulation }); }); console.log("Transaction successfully committed!"); } catch (e) { console.log("Transaction failed: ", e); }
Web
// Create a reference to the SF doc. var sfDocRef = db.collection("cities").doc("SF"); // Uncomment to initialize the doc. // sfDocRef.set({ population: 0 }); return db.runTransaction((transaction) => { // This code may get re-run multiple times if there are conflicts. return transaction.get(sfDocRef).then((sfDoc) => { if (!sfDoc.exists) { throw "Document does not exist!"; } // Add one person to the city population. // Note: this could be done without a transaction // by updating the population using FieldValue.increment() var newPopulation = sfDoc.data().population + 1; transaction.update(sfDocRef, { population: newPopulation }); }); }).then(() => { console.log("Transaction successfully committed!"); }).catch((error) => { console.log("Transaction failed: ", error); });
Swift
let sfReference = db.collection("cities").document("SF") do { let _ = try await db.runTransaction({ (transaction, errorPointer) -> Any? in let sfDocument: DocumentSnapshot do { try sfDocument = transaction.getDocument(sfReference) } catch let fetchError as NSError { errorPointer?.pointee = fetchError return nil } guard let oldPopulation = sfDocument.data()?["population"] as? Int else { let error = NSError( domain: "AppErrorDomain", code: -1, userInfo: [ NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" ] ) errorPointer?.pointee = error return nil } // Note: this could be done without a transaction // by updating the population using FieldValue.increment() transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference) return nil }) print("Transaction successfully committed!") } catch { print("Transaction failed: \(error)") }
Objective-C
FIRDocumentReference *sfReference = [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [self.db runTransactionWithBlock:^id (FIRTransaction *transaction, NSError **errorPointer) { FIRDocumentSnapshot *sfDocument = [transaction getDocument:sfReference error:errorPointer]; if (*errorPointer != nil) { return nil; } if (![sfDocument.data[@"population"] isKindOfClass:[NSNumber class]]) { *errorPointer = [NSError errorWithDomain:@"AppErrorDomain" code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Unable to retreive population from snapshot" }]; return nil; } NSInteger oldPopulation = [sfDocument.data[@"population"] integerValue]; // Note: this could be done without a transaction // by updating the population using FieldValue.increment() [transaction updateData:@{ @"population": @(oldPopulation + 1) } forDocument:sfReference]; return nil; } completion:^(id result, NSError *error) { if (error != nil) { NSLog(@"Transaction failed: %@", error); } else { NSLog(@"Transaction successfully committed!"); } }];
Kotlin+KTX
val sfDocRef = db.collection("cities").document("SF") db.runTransaction { transaction -> val snapshot = transaction.get(sfDocRef) // Note: this could be done without a transaction // by updating the population using FieldValue.increment() val newPopulation = snapshot.getDouble("population")!! + 1 transaction.update(sfDocRef, "population", newPopulation) // Success null }.addOnSuccessListener { Log.d(TAG, "Transaction success!") } .addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) }
Java
final DocumentReference sfDocRef = db.collection("cities").document("SF"); db.runTransaction(new Transaction.Function<Void>() { @Override public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException { DocumentSnapshot snapshot = transaction.get(sfDocRef); // Note: this could be done without a transaction // by updating the population using FieldValue.increment() double newPopulation = snapshot.getDouble("population") + 1; transaction.update(sfDocRef, "population", newPopulation); // Success return null; } }).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "Transaction success!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Transaction failure.", e); } });
Dart
final sfDocRef = db.collection("cities").doc("SF"); db.runTransaction((transaction) async { final snapshot = await transaction.get(sfDocRef); // Note: this could be done without a transaction // by updating the population using FieldValue.increment() final newPopulation = snapshot.get("population") + 1; transaction.update(sfDocRef, {"population": newPopulation}); }).then( (value) => print("DocumentSnapshot successfully updated!"), onError: (e) => print("Error updating document $e"), );
Java
Python
Python
C++
DocumentReference sf_doc_ref = db->Collection("cities").Document("SF"); db->RunTransaction([sf_doc_ref](Transaction& transaction, std::string& out_error_message) -> Error { Error error = Error::kErrorOk; DocumentSnapshot snapshot = transaction.Get(sf_doc_ref, &error, &out_error_message); // Note: this could be done without a transaction by updating the // population using FieldValue::Increment(). std::int64_t new_population = snapshot.Get("population").integer_value() + 1; transaction.Update( sf_doc_ref, {{"population", FieldValue::Integer(new_population)}}); return Error::kErrorOk; }).OnCompletion([](const Future<void>& future) { if (future.error() == Error::kErrorOk) { std::cout << "Transaction success!" << std::endl; } else { std::cout << "Transaction failure: " << future.error_message() << std::endl; } });
Node.js के लिए
शुरू करें
PHP
Unity
DocumentReference cityRef = db.Collection("cities").Document("SF"); db.RunTransactionAsync(transaction => { return transaction.GetSnapshotAsync(cityRef).ContinueWith((snapshotTask) => { DocumentSnapshot snapshot = snapshotTask.Result; long newPopulation = snapshot.GetValue<long>("Population") + 1; Dictionary<string, object> updates = new Dictionary<string, object> { { "Population", newPopulation} }; transaction.Update(cityRef, updates); }); });
C#
Ruby
लेन-देन से बाहर जानकारी पास करना
अपने ट्रांज़ैक्शन फ़ंक्शन में ऐप्लिकेशन की स्थिति में बदलाव न करें. ऐसा करने से एक साथ कई काम करने की समस्याएं आएंगी, क्योंकि ट्रांज़ैक्शन फ़ंक्शन कई बार चल सकते हैं और इसके यूज़र इंटरफ़ेस (यूआई) थ्रेड पर चलने की कोई गारंटी नहीं है. इसके बजाय, अपने लेन-देन फ़ंक्शन से अपनी ज़रूरत की जानकारी भेजें. लेन-देन से जानकारी पास करने का तरीका दिखाने के लिए, नीचे दिए गए उदाहरण में पिछले उदाहरण की मदद ली गई है:
Web
import { doc, runTransaction } from "firebase/firestore"; // Create a reference to the SF doc. const sfDocRef = doc(db, "cities", "SF"); try { const newPopulation = await runTransaction(db, async (transaction) => { const sfDoc = await transaction.get(sfDocRef); if (!sfDoc.exists()) { throw "Document does not exist!"; } const newPop = sfDoc.data().population + 1; if (newPop <= 1000000) { transaction.update(sfDocRef, { population: newPop }); return newPop; } else { return Promise.reject("Sorry! Population is too big"); } }); console.log("Population increased to ", newPopulation); } catch (e) { // This will be a "population is too big" error. console.error(e); }
Web
// Create a reference to the SF doc. var sfDocRef = db.collection("cities").doc("SF"); db.runTransaction((transaction) => { return transaction.get(sfDocRef).then((sfDoc) => { if (!sfDoc.exists) { throw "Document does not exist!"; } var newPopulation = sfDoc.data().population + 1; if (newPopulation <= 1000000) { transaction.update(sfDocRef, { population: newPopulation }); return newPopulation; } else { return Promise.reject("Sorry! Population is too big."); } }); }).then((newPopulation) => { console.log("Population increased to ", newPopulation); }).catch((err) => { // This will be an "population is too big" error. console.error(err); });
Swift
let sfReference = db.collection("cities").document("SF") do { let object = try await db.runTransaction({ (transaction, errorPointer) -> Any? in let sfDocument: DocumentSnapshot do { try sfDocument = transaction.getDocument(sfReference) } catch let fetchError as NSError { errorPointer?.pointee = fetchError return nil } guard let oldPopulation = sfDocument.data()?["population"] as? Int else { let error = NSError( domain: "AppErrorDomain", code: -1, userInfo: [ NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" ] ) errorPointer?.pointee = error return nil } // Note: this could be done without a transaction // by updating the population using FieldValue.increment() let newPopulation = oldPopulation + 1 guard newPopulation <= 1000000 else { let error = NSError( domain: "AppErrorDomain", code: -2, userInfo: [NSLocalizedDescriptionKey: "Population \(newPopulation) too big"] ) errorPointer?.pointee = error return nil } transaction.updateData(["population": newPopulation], forDocument: sfReference) return newPopulation }) print("Population increased to \(object!)") } catch { print("Error updating population: \(error)") }
Objective-C
FIRDocumentReference *sfReference = [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [self.db runTransactionWithBlock:^id (FIRTransaction *transaction, NSError **errorPointer) { FIRDocumentSnapshot *sfDocument = [transaction getDocument:sfReference error:errorPointer]; if (*errorPointer != nil) { return nil; } if (![sfDocument.data[@"population"] isKindOfClass:[NSNumber class]]) { *errorPointer = [NSError errorWithDomain:@"AppErrorDomain" code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Unable to retreive population from snapshot" }]; return nil; } NSInteger population = [sfDocument.data[@"population"] integerValue]; population++; if (population >= 1000000) { *errorPointer = [NSError errorWithDomain:@"AppErrorDomain" code:-2 userInfo:@{ NSLocalizedDescriptionKey: @"Population too big" }]; return @(population); } [transaction updateData:@{ @"population": @(population) } forDocument:sfReference]; return nil; } completion:^(id result, NSError *error) { if (error != nil) { NSLog(@"Transaction failed: %@", error); } else { NSLog(@"Population increased to %@", result); } }];
Kotlin+KTX
val sfDocRef = db.collection("cities").document("SF") db.runTransaction { transaction -> val snapshot = transaction.get(sfDocRef) val newPopulation = snapshot.getDouble("population")!! + 1 if (newPopulation <= 1000000) { transaction.update(sfDocRef, "population", newPopulation) newPopulation } else { throw FirebaseFirestoreException( "Population too high", FirebaseFirestoreException.Code.ABORTED, ) } }.addOnSuccessListener { result -> Log.d(TAG, "Transaction success: $result") }.addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) }
Java
final DocumentReference sfDocRef = db.collection("cities").document("SF"); db.runTransaction(new Transaction.Function<Double>() { @Override public Double apply(@NonNull Transaction transaction) throws FirebaseFirestoreException { DocumentSnapshot snapshot = transaction.get(sfDocRef); double newPopulation = snapshot.getDouble("population") + 1; if (newPopulation <= 1000000) { transaction.update(sfDocRef, "population", newPopulation); return newPopulation; } else { throw new FirebaseFirestoreException("Population too high", FirebaseFirestoreException.Code.ABORTED); } } }).addOnSuccessListener(new OnSuccessListener<Double>() { @Override public void onSuccess(Double result) { Log.d(TAG, "Transaction success: " + result); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Transaction failure.", e); } });
Dart
final sfDocRef = db.collection("cities").doc("SF"); db.runTransaction((transaction) { return transaction.get(sfDocRef).then((sfDoc) { final newPopulation = sfDoc.get("population") + 1; transaction.update(sfDocRef, {"population": newPopulation}); return newPopulation; }); }).then( (newPopulation) => print("Population increased to $newPopulation"), onError: (e) => print("Error updating document $e"), );
Java
Python
Python
C++
// This is not yet supported.
Node.js के लिए
शुरू करें
PHP
Unity
DocumentReference cityRef = db.Collection("cities").Document("SF"); db.RunTransactionAsync(transaction => { return transaction.GetSnapshotAsync(cityRef).ContinueWith((task) => { long newPopulation = task.Result.GetValue<long>("Population") + 1; if (newPopulation <= 1000000) { Dictionary<string, object> updates = new Dictionary<string, object> { { "Population", newPopulation} }; transaction.Update(cityRef, updates); return true; } else { return false; } }); }).ContinueWith((transactionResultTask) => { if (transactionResultTask.Result) { Console.WriteLine("Population updated successfully."); } else { Console.WriteLine("Sorry! Population is too big."); } });
C#
Ruby
लेन-देन नहीं किया जा सका
लेन-देन इन वजहों से पूरा नहीं हो सकता:
- लेन-देन में, लिखने के बाद पढ़ने की कार्रवाइयां शामिल होती हैं. रीड ऑपरेशन हमेशा किसी भी ऑपरेशन से पहले आने चाहिए.
- ट्रांज़ैक्शन में वह दस्तावेज़ पढ़ा गया जिसमें ट्रांज़ैक्शन के बाहर बदलाव किया गया था. इस स्थिति में, लेन-देन फिर से अपने-आप चलने लगेगा. लेन-देन की सीमित संख्या में फिर से कोशिश की जाती है.
यह ट्रांज़ैक्शन, 10 एमबी की तय सीमा से ज़्यादा का है.
ट्रांज़ैक्शन का साइज़, ट्रांज़ैक्शन से जुड़े दस्तावेज़ों और इंडेक्स एंट्री के साइज़ पर निर्भर करता है. मिटाने की कार्रवाई में, टारगेट दस्तावेज़ का साइज़ और कार्रवाई के जवाब में मिटाई गई इंडेक्स एंट्री का साइज़ शामिल होता है.
ट्रांज़ैक्शन पूरा न होने पर गड़बड़ी का मैसेज मिलता है और डेटाबेस में कुछ भी नहीं लिखा जाता है. आपको ट्रांज़ैक्शन को रोल बैक करने की ज़रूरत नहीं है. Cloud Firestore यह काम अपने-आप करता है.
एक साथ ग्रुप या बैच में लिखने की सुविधा
अगर आपको अपने ऑपरेशन सेट में कोई भी दस्तावेज़ पढ़ने की ज़रूरत नहीं है, तो आप एक ऐसे बैच के रूप में कई लिखने के लिए कार्रवाइयां कर सकते हैं जिसमें set()
, update()
या delete()
कार्रवाइयों का कोई भी कॉम्बिनेशन शामिल हो. राइट का एक बैच अपने-आप पूरा होता है और
एक से ज़्यादा दस्तावेज़ों पर लिखा जा सकता है. इस उदाहरण में, लिखने के लिए एक बैच बनाने और उसे कॉन्फ़िगर करने का तरीका बताया गया है:
Web
import { writeBatch, doc } from "firebase/firestore"; // Get a new write batch const batch = writeBatch(db); // Set the value of 'NYC' const nycRef = doc(db, "cities", "NYC"); batch.set(nycRef, {name: "New York City"}); // Update the population of 'SF' const sfRef = doc(db, "cities", "SF"); batch.update(sfRef, {"population": 1000000}); // Delete the city 'LA' const laRef = doc(db, "cities", "LA"); batch.delete(laRef); // Commit the batch await batch.commit();
Web
// Get a new write batch var batch = db.batch(); // Set the value of 'NYC' var nycRef = db.collection("cities").doc("NYC"); batch.set(nycRef, {name: "New York City"}); // Update the population of 'SF' var sfRef = db.collection("cities").doc("SF"); batch.update(sfRef, {"population": 1000000}); // Delete the city 'LA' var laRef = db.collection("cities").doc("LA"); batch.delete(laRef); // Commit the batch batch.commit().then(() => { // ... });
Swift
// Get new write batch let batch = db.batch() // Set the value of 'NYC' let nycRef = db.collection("cities").document("NYC") batch.setData([:], forDocument: nycRef) // Update the population of 'SF' let sfRef = db.collection("cities").document("SF") batch.updateData(["population": 1000000 ], forDocument: sfRef) // Delete the city 'LA' let laRef = db.collection("cities").document("LA") batch.deleteDocument(laRef) // Commit the batch do { try await batch.commit() print("Batch write succeeded.") } catch { print("Error writing batch: \(error)") }
Objective-C
// Get new write batch FIRWriteBatch *batch = [self.db batch]; // Set the value of 'NYC' FIRDocumentReference *nycRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"NYC"]; [batch setData:@{} forDocument:nycRef]; // Update the population of 'SF' FIRDocumentReference *sfRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [batch updateData:@{ @"population": @1000000 } forDocument:sfRef]; // Delete the city 'LA' FIRDocumentReference *laRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"LA"]; [batch deleteDocument:laRef]; // Commit the batch [batch commitWithCompletion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error writing batch %@", error); } else { NSLog(@"Batch write succeeded."); } }];
Kotlin+KTX
val nycRef = db.collection("cities").document("NYC") val sfRef = db.collection("cities").document("SF") val laRef = db.collection("cities").document("LA") // Get a new write batch and commit all write operations db.runBatch { batch -> // Set the value of 'NYC' batch.set(nycRef, City()) // Update the population of 'SF' batch.update(sfRef, "population", 1000000L) // Delete the city 'LA' batch.delete(laRef) }.addOnCompleteListener { // ... }
Java
// Get a new write batch WriteBatch batch = db.batch(); // Set the value of 'NYC' DocumentReference nycRef = db.collection("cities").document("NYC"); batch.set(nycRef, new City()); // Update the population of 'SF' DocumentReference sfRef = db.collection("cities").document("SF"); batch.update(sfRef, "population", 1000000L); // Delete the city 'LA' DocumentReference laRef = db.collection("cities").document("LA"); batch.delete(laRef); // Commit the batch batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // ... } });
Dart
// Get a new write batch final batch = db.batch(); // Set the value of 'NYC' var nycRef = db.collection("cities").doc("NYC"); batch.set(nycRef, {"name": "New York City"}); // Update the population of 'SF' var sfRef = db.collection("cities").doc("SF"); batch.update(sfRef, {"population": 1000000}); // Delete the city 'LA' var laRef = db.collection("cities").doc("LA"); batch.delete(laRef); // Commit the batch batch.commit().then((_) { // ... });
Java
Python
Python
C++
// Get a new write batch WriteBatch batch = db->batch(); // Set the value of 'NYC' DocumentReference nyc_ref = db->Collection("cities").Document("NYC"); batch.Set(nyc_ref, {}); // Update the population of 'SF' DocumentReference sf_ref = db->Collection("cities").Document("SF"); batch.Update(sf_ref, {{"population", FieldValue::Integer(1000000)}}); // Delete the city 'LA' DocumentReference la_ref = db->Collection("cities").Document("LA"); batch.Delete(la_ref); // Commit the batch batch.Commit().OnCompletion([](const Future<void>& future) { if (future.error() == Error::kErrorOk) { std::cout << "Write batch success!" << std::endl; } else { std::cout << "Write batch failure: " << future.error_message() << std::endl; } });
Node.js के लिए
शुरू करें
PHP
Unity
WriteBatch batch = db.StartBatch(); // Set the data for NYC DocumentReference nycRef = db.Collection("cities").Document("NYC"); Dictionary<string, object> nycData = new Dictionary<string, object> { { "name", "New York City" } }; batch.Set(nycRef, nycData); // Update the population for SF DocumentReference sfRef = db.Collection("cities").Document("SF"); Dictionary<string, object> updates = new Dictionary<string, object> { { "Population", 1000000} }; batch.Update(sfRef, updates); // Delete LA DocumentReference laRef = db.Collection("cities").Document("LA"); batch.Delete(laRef); // Commit the batch batch.CommitAsync();
C#
Ruby
बैच वाले राइट में 500 कार्रवाइयां हो सकती हैं. बैच में हर कार्रवाई की गिनती, आपके Cloud Firestore के इस्तेमाल के हिसाब से अलग-अलग की जाती है.
लेन-देन की तरह ही, एक साथ कई दस्तावेज़ भी एक साथ लिखें जाते हैं. ट्रांज़ैक्शन के उलट, बैच में लिखे गए कॉन्टेंट को यह पक्का करने की ज़रूरत नहीं होती कि पढ़े गए दस्तावेज़ में कोई बदलाव न हो. इससे असफल होने की संभावना कम हो जाती है. दोबारा कोशिश करने या कई बार कोशिश करने पर असफल होने की संभावना नहीं होती. बैच में लिखने की सुविधा, उपयोगकर्ता के डिवाइस के ऑफ़लाइन होने पर भी काम करती है.
ऐटॉमिक ऑपरेशंस के लिए डेटा की पुष्टि
मोबाइल/वेब क्लाइंट लाइब्रेरी के लिए, Cloud Firestore के सुरक्षा नियमों का इस्तेमाल करके डेटा की पुष्टि की जा सकती है. आपके पास यह पक्का करने का विकल्प होता है कि मिलते-जुलते दस्तावेज़ों को हमेशा अपने-आप अपडेट किया जाए. साथ ही, ये लेन-देन या बैच में लिखे गए दस्तावेज़ों के तौर पर भी अपडेट होते रहें.
कार्रवाइयों का एक सेट पूरा होने के बाद, लेकिन Cloud Firestore के कार्रवाई करने से पहले, किसी दस्तावेज़ की स्थिति को ऐक्सेस करने और उसकी पुष्टि करने के लिए, getAfter()
के सुरक्षा नियम फ़ंक्शन का इस्तेमाल करें.
उदाहरण के लिए, मान लें कि cities
उदाहरण के डेटाबेस में countries
कलेक्शन भी मौजूद है. हर country
दस्तावेज़ में last_updated
फ़ील्ड का इस्तेमाल किया जाता है, ताकि यह ट्रैक किया जा सके कि उस देश से जुड़े किसी शहर को पिछली बार कब अपडेट किया गया था. सुरक्षा के यहां दिए गए नियमों के मुताबिक, city
दस्तावेज़ में किए जाने वाले बदलाव, संबंधित देश का last_updated
फ़ील्ड भी अपने-आप अपडेट होने चाहिए:
service cloud.firestore { match /databases/{database}/documents { // If you update a city doc, you must also // update the related country's last_updated field. match /cities/{city} { allow write: if request.auth != null && getAfter( /databases/$(database)/documents/countries/$(request.resource.data.country) ).data.last_updated == request.time; } match /countries/{country} { allow write: if request.auth != null; } } }
सुरक्षा के नियमों की सीमाएं
लेन-देन या बैच में लिखने के सुरक्षा नियमों के तहत, पूरे ऐटॉमिक ऑपरेशन के लिए दस्तावेज़ को ऐक्सेस करने की सीमा 20 है. इसके अलावा, बैच में हर दस्तावेज़ के लिए, सामान्य तौर पर 10 कॉल करने की सीमा तय है.
उदाहरण के लिए, चैट ऐप्लिकेशन के लिए इन नियमों को ध्यान में रखें:
service cloud.firestore { match /databases/{db}/documents { function prefix() { return /databases/{db}/documents; } match /chatroom/{roomId} { allow read, write: if request.auth != null && roomId in get(/$(prefix())/users/$(request.auth.uid)).data.chats || exists(/$(prefix())/admins/$(request.auth.uid)); } match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId || exists(/$(prefix())/admins/$(request.auth.uid)); } match /admins/{userId} { allow read, write: if request.auth != null && exists(/$(prefix())/admins/$(request.auth.uid)); } } }
नीचे दिए गए स्निपेट में, डेटा ऐक्सेस के कुछ पैटर्न के लिए, दस्तावेज़ को ऐक्सेस करने के लिए इस्तेमाल किए जाने वाले कॉल की संख्या बताई गई है:
// 0 document access calls used, because the rules evaluation short-circuits // before the exists() call is invoked. db.collection('user').doc('myuid').get(...); // 1 document access call used. The maximum total allowed for this call // is 10, because it is a single document request. db.collection('chatroom').doc('mygroup').get(...); // Initializing a write batch... var batch = db.batch(); // 2 document access calls used, 10 allowed. var group1Ref = db.collection("chatroom").doc("group1"); batch.set(group1Ref, {msg: "Hello, from Admin!"}); // 1 document access call used, 10 allowed. var newUserRef = db.collection("users").doc("newuser"); batch.update(newUserRef, {"lastSignedIn": new Date()}); // 1 document access call used, 10 allowed. var removedAdminRef = db.collection("admin").doc("otheruser"); batch.delete(removedAdminRef); // The batch used a total of 2 + 1 + 1 = 4 document access calls, out of a total // 20 allowed. batch.commit();
ज़्यादा जानकारी के लिए, एक साथ कई फ़ाइलों को लिखने और एक साथ लिखने, एक साथ कई फ़ाइलों को लिखने, और लेन-देन के ओवरलैप होने की वजह से होने वाली गड़बड़ियों, और अन्य समस्याओं को हल करने के बारे में ज़्यादा जानने के लिए, समस्या हल करने वाला पेज देखें.