Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.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_Reactjs_Firebase_Google Cloud Firestore - Fatal编程技术网

Javascript Firestore-如何基于特定字段检查文档是否存在

Javascript Firestore-如何基于特定字段检查文档是否存在,javascript,reactjs,firebase,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Firestore,我想要实现的是,根据liker_id这样的字段检查文档是否存在,如果存在,则返回,如果不存在,则使用liker_id创建一个新文档 我尝试了snapshot.exists和doc.exists,但它们似乎给出了一些奇怪的行为,其中console.log没有被触发,或者集合仍然添加文档,即使文档已经存在 const liker = db .collection("post") .doc('ubxL0nDCLHgrtEyQ5TEV') .collection("votes") .wh

我想要实现的是,根据liker_id这样的字段检查文档是否存在,如果存在,则返回,如果不存在,则使用liker_id创建一个新文档

我尝试了snapshot.exists和doc.exists,但它们似乎给出了一些奇怪的行为,其中console.log没有被触发,或者集合仍然添加文档,即使文档已经存在

const liker = db
  .collection("post")
  .doc('ubxL0nDCLHgrtEyQ5TEV')
  .collection("votes")
  .where("liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3")
  .get()
  .then(snapshot => {
    snapshot.forEach(doc => {
      if (doc.exists) {
        console.log("exist");
      } else {
        console.log("not exist");
      }
    });
  })
  .catch(error => {
    console.log(error);
  });

你能试试这样的代码吗

const liker = db
  .collection("post")
  .doc('ubxL0nDCLHgrtEyQ5TEV')
  .collection("votes")
  .where("liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3")
  .get()
  .then(snapshot => {
    const data = snapshot.val();
    data.forEach(doc => {
      if (doc.exists) {
        console.log("exist");
      } else {
        console.log("not exist");
      }
    });
  })
  .catch(error => {
    console.log(error);
  });

还有一个类似的问题,我不确定我是否理解你所看到的行为。您是说即使已经存在具有
“liker_id”、“==”、“user-tve8mmru47cnfo4xbl9yqee4xb3”
的文档,也会打印
不存在?您需要做的只是检查,而不需要循环。我尝试了“snapshot.empty”,但无论集合是否为空,它都只返回“true”。
const data=snapshot.val()
是实时数据库的代码,而OP使用的是CloudFireStore。虽然这两个数据库都是Firebase的一部分,但它们有不同的API。