[英]Is there anyway to use StartAt with Firestore queries if you don't have a document reference
[英]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 代表的文檔上創建事務?
一旦您實際執行該查詢,該參考就很容易獲得。 您可以簡單地:
ref
屬性獲取文檔的引用,即DocumentReference 您需要等待 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.