首页 > 解决方案 > Firestore - 如何根据特定字段检查文档是否存在

问题描述

我想要实现的是根据 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);
  });

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


你会试试这样的代码吗?

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);
  });

推荐阅读