Firestore-如何根据特定字段检查文档是否存在

时间:2020-02-24 14:45:33

标签: 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")
  .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);
  });

1 个答案:

答案 0 :(得分:0)

您会尝试这样的代码吗?

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