简体   繁体   English

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

[英]Firestore - How to check if a document exist based on a specific field

What I want to achieve is to check if a document exist based on a field like liker_id and if it exist then return and if not then create a new document with the liker_id.我想要实现的是根据像liker_id这样的字段检查文档是否存在,如果存在则返回,如果不存在则使用liker_id创建一个新文档。

I've tried both snapshot.exists and doc.exists but they seem to give weird behaviors where the console.log doesn't get triggered or collection still adds document even though it already exists.我已经尝试过 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);
  });

Would you try the code like this?你会尝试这样的代码吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ionic firestore如何检查firestore中是否存在文档ID - Ionic firestore how to check document id exist in firestore or not 如何检查文档参考的javascript数组中是否存在Firestore文档参考? - How to check if a Firestore Document reference exist in a javascript array of Document references? 如何检查firestore文档中是否存在字段? - How to check whether field exists or not in the firestore document? 如何检查Firestore文档是否具有特定字段 - How to check if firestore document have a particular field 如何检查文档是否存在与mongodb中的特定字段 - How to check if document exist with particular field in mongodb 如何检查 JS 中的 firestore(不是文档)中是否存在集合 - How do I check if collection exist in firestore (not document) in JS 如何通过文档 ID 从 firestore 网站获取特定字段数据 - How get specific Field data by document id from firestore website 如何从基于带有 firestore 的字段的集合中获取文档? - How to get document from a collection based on a field with firestore? 检查包含具有特定值的字段的文档是否存在的最佳方法是什么 - Firestore? - Whats the best way to check for the existence of a document which contains a field with a specific value - Firestore? 基于 Firestore 中的文档字段限制数据 - Limiting data based on document field in Firestore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM