Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Firestore事务在获取和设置一个曾经存在的文档时失败_Javascript_Google Cloud Firestore_Transactions - Fatal编程技术网

Javascript Firestore事务在获取和设置一个曾经存在的文档时失败

Javascript Firestore事务在获取和设置一个曾经存在的文档时失败,javascript,google-cloud-firestore,transactions,Javascript,Google Cloud Firestore,Transactions,给定一个简单事务,该事务调用get,然后调用set,将事务中的同一文档引用调用到不存在文档的db 代码如下: var db = firebase.firestore(); var docRef = db.collection("devtest").doc("doc-1"); return db.runTransaction((transaction) => { return transaction.get(docRef).then((doc

给定一个简单事务,该事务调用
get
,然后调用
set
,将事务中的同一文档引用调用到不存在文档的db

代码如下:

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" }); }); });
在浏览器中针对emulator数据库运行此代码可以正常工作。再次跑步再次奏效

但是,当我(手动)从数据库中删除文档,然后再次运行代码时,它会失败,原因是:

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)
重新加载浏览器页面无法解决此问题。但是重新启动仿真器会这样做-直到文档再次被删除

为什么会这样


这就像一只虫子。“文档从不存在”和“文档存在并被删除”之间的行为应该没有区别。

只有在有文档要获取时,事务才会成功。如果要更新文档(如果它存在)并设置它(如果不存在),请尝试使用
catch
块来设置文档(如果它不存在)。您可能还想在这里添加一些错误处理,以防错误与尚不存在的文档无关

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) => {
    docRef.set(docRef, {aValue: "hello world"});
  });
});

您可能希望使用
if(!doc.exists){return null;}
检查文档是否在
.get
之后存在。如果这对你有效,我会把它作为答案发布。但是我想做
transaction.set(…
即使该文档不存在。您的问题还不清楚。请更新它,以显示如果存在现有文档以及如果没有现有文档,预期的流应该是什么。我不关心该行为。我只是认为当该文档不存在时,以及当该文档存在并被删除时,应该是相同的行为eleted。