簡體   English   中英

Firestore交易在單個交易中更新多個集合

[英]Firestore transaction update multiple collections in a single transaction

如何使用搜索到的單個交易更新Firestore中的多個集合,但沒有得到任何答案。 是否可以在單個事務中更新多個集合?

我想一次在教室和學生集合中更新 branch.name 在此處輸入圖片說明

在此處輸入圖片說明

如Node.js客戶端庫update()方法的文檔所述,它返回一個Transaction ,“ 用於鏈接方法調用” (請注意,Admin SDK的update()方法的行為完全相同)。

因此,例如,如果在事務中您想從課堂文檔中獲取價值,增加它並使用它來更新來自兩個不同集合( classroomsstudents )的兩個文檔,您將執行以下操作:

const db = firebase.firestore();  //or admin.firestore() in a Cloud Function
const docRef1 = db.collection('classrooms').doc('classroomDocId');
const docRef2 = db.collection('students').doc('studentDocId');


let transaction = db.runTransaction(t => {
  let newNumericValue;
  return t.get(docRef1 )
    .then(doc => {
      newNumericValue = doc.data().numericValue + 1;  //You calculate the new value
      return t.update(docRef1 , {numericValue : newNumericValue});
    }).then(t => {
      return t.update(docRef2 , {numericValue : newNumericValue});
    });
}).then(result => {
  console.log('Transaction success!' + result);
}).catch(err => {
  console.log('Transaction failure:', err);
});

請注意,如果您需要在多次更新之前進行多次讀取,則“使用事務時, 讀取操作必須先於寫入操作”


另一方面, 如果您只是想在不讀取一個或多個值的情況下更新多個文檔(您在問題中說“您希望在教​​室和學生集合中一次更新一次branch.name”),則不需要使用交易。 只需使用批處理write即可 ,如下所示:

let batch = db.batch();

let cRef = db.collection('classrooms').doc('classroomDocId');
batch.set(cRef, {branch.name: 'newName'});

let sRef = db.collection('students').doc('studentDocId');
batch.update(sRef, {branch.name: 'newName'});

return batch.commit().then(function () {
  // ...
});

更新您的評論

在您的Cloud Function中,您可以很好地鏈接不同的Firestore查詢(使用where() ),並在每個then()填充批次,然后在最后一個then()提交批次。 請參見下面的示例(僅使用正確的查詢進行調整):

 let batch = admin.firestore().batch();

 return admin.firestore().collection('students').where('branch.id', '==', documentId).get()
 .then((querySnapshot) => {
    querySnapshot.forEach((doc) => { 
        batch.update(doc.ref, {branch: {id: documentId, name: after.name}}); 
    });
    return admin.firestore().collection('student_public').where('branch.id', '==', documentId).get();
 })
 .then((querySnapshot) => {
    querySnapshot.forEach((doc) => { 
        batch.update(doc.ref, {branch: {id: documentId, name: after.name}}); 
    });
    return batch.commit() 
 })
 .catch(err => { console.log('error===>', err); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM