【发布时间】:2020-08-01 20:57:26
【问题描述】:
我有一个文档,我用这样的查询获取:
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 变量,但我不能,因为一个是文档引用,另一个是承诺。 如何在 myPromise 代表的文档上创建事务?
【问题讨论】:
标签: javascript node.js firebase google-cloud-firestore