Firestore 事务在获取和设置曾经存在的文档时失败 [英] Firestore transaction fails on get and set of a document which once existed
问题描述
给定一个简单的事务,它调用 get
然后 set
将事务中的相同文档引用到文档不存在的数据库.
Given a simple transaction which calls get
and then set
for the same document reference in a transaction to a db where the document does not exist.
这是代码:
var db = firebase.firestore();
var docRef = db.collection("devtest").doc("doc-1");
return db.runTransaction((transaction) => {
return transaction.get(docRef).then((doc) => {
transaction.set(docRef, {
aValue: "hello world" }); }); });
在浏览器中针对模拟器数据库运行此代码工作正常.再次运行再次起作用.
Running this code in the browser against the emulator database works fine. Running again works again.
但是当我(手动)从数据库中删除文档然后再次运行代码时,它失败了:
But when I (manually) delete the document from the database and then run the code again, it fails with:
FirebaseError: the stored version (1619370082687231) does not match the required base version (0)
at new zr (http://localhost:50001/__/firebase/8.2.3/firebase-firestore.js:1:47931)
重新加载浏览器页面并不能解决此问题.但是重新启动模拟器确实可以 - 直到文档再次被删除.
Reloading the browser page does not fix this issue. But restarting the emulator does - until the document gets deleted again.
这是为什么?
这看起来像是一个错误.文档从不存在"和文档从不存在"之间的行为应该没有区别.和文档存在并被删除".
This seams like a bug. There should be no difference in behavior, between a "document never existed" and "document existed and was deleted".
推荐答案
只有当有文档要get
时,事务才会成功.如果要更新文档(如果存在)并设置它(如果不存在),请尝试使用 catch
块来设置文档(如果它不存在).您可能还想在此处添加一些错误处理,以防万一错误与尚不存在的文档无关
The transaction will only succeed if there is a document to get
. If you want to update the document if it exists and set it if it doesn't, try using the catch
block to set the document, if it doesn't already exist. You may also want to add some error handling in here, just in case the error isn't related to a document which doesn't yet exist
var db = firebase.firestore();
var docRef = db.doc("devtest/doc-1");
return db.runTransaction((transaction) => {
return transaction.get(docRef)
.then((doc) => {
transaction.set(docRef, {aValue: "hello world"});
})
.catch((err) => {
transaction.set(docRef, {aValue: "hello world"});
});
});
这篇关于Firestore 事务在获取和设置曾经存在的文档时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!