簡體   English   中英

Firestore:如何使用事務讀取然后寫入我沒有參考的文檔?

[英]Firestore: How can I use a transaction to read and then write to a document that I don't have a reference to?

我有一個文檔,我用這樣的查詢獲取:

var myPromise = db.collection("games").where("started", "==", false).orderBy("created").limit(1).get()

我需要創建一個從該文檔讀取然后寫入的事務。 例如(取自文檔):

// 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(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(sfDocRef).then(function(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(function() {
    console.log("Transaction successfully committed!");
}).catch(function(error) {
    console.log("Transaction failed: ", error);
});

我想用 myPromise 變量替換 sfDocRef 變量,但我不能,因為一個是文檔引用,另一個是 promise。 如何在 myPromise 代表的文檔上創建事務?

一旦您實際執行該查詢,該參考就很容易獲得。 您可以簡單地:

  1. 像現在一樣執行查詢
  2. 在查詢結果中找到DocumentSnapshot (就像處理查詢結果時通常那樣)
  3. 使用 DocumentSnapshot 的ref屬性獲取文檔的引用,即DocumentReference
  4. 在事務中使用該引用。

您需要等待 promise 解決,例如通過附加一個then回調:

myPromise.then((querySnapshot) => {
  let ref = querySnapshot.documents[0].ref;
  return db.runTransaction(function(transaction) {
    return transaction.get(ref).then(function(sfDoc) {
        if (!sfDoc.exists) {
            throw "Document does not exist!";
        }
        var newPopulation = sfDoc.data().population + 1;
        transaction.update(sfDocRef, { population: newPopulation });
    });
  }).then(function() {
    console.log("Transaction successfully committed!");
  }).catch(function(error) {
    console.log("Transaction failed: ", error);
  });
});

querySnapshot.documents[0].ref假定只有一個匹配的文檔,或者您只關心第一個文檔。 如果您關心的內容可能更多,則需要遍歷查詢快照中的文檔。

如果(且僅當)您希望事務確保該文檔在查詢之間和您將其寫入事務中時未修改,您仍然需要在事務中get特定文檔。 如果不需要,您可以使用QueryDocumentSnapshot中的QuerySnapshot

暫無
暫無

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

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