【问题标题】:How to check if a document contains a property in Cloud Firestore?如何检查文档是否包含 Cloud Firestore 中的属性?
【发布时间】:2019-03-29 13:23:24
【问题描述】:

我想知道是否有办法检查 Cloud Firestore 文档中是否存在属性。 document.contains("property_name") 之类的东西,或者是否存在文档属性。

【问题讨论】:

    标签: node.js firebase google-cloud-firestore


    【解决方案1】:

    要解决这个问题,您可以像这样简单地检查 DocumentSnapshot 对象的无效性:

    var yourRef = db.collection('yourCollection').doc('yourDocument');
    var getDoc = yourRef.get()
        .then(doc => {
          if (!doc.exists) {
            console.log('No such document!');
          } else {
            if(doc.get('yourPropertyName') != null) {
              console.log('Document data:', doc.data());
            } else {
              console.log('yourPropertyName does not exist!');
            }
          }
        })
        .catch(err => {
          console.log('Error getting document', err);
        });
    

    【讨论】:

    • 嗨,戴安!你有没有试过我上面的解决方案,它有效吗?
    • 亚历克斯,对不起...我做了,但我忘记将其标记为解决方案,但对我有用。谢谢
    【解决方案2】:

    你可以像下面的 sn-p 一样使用in 运算符

      const ref = admin.firestore().collection('yourCollectionName').doc('yourDocName')
      try {
        const res = await ref.get()
        const data = res.data()    
        if (!res.exists) {
          if (!("yourPropertyName" in data)) {
             // Do your thing
          }
        } else {
             // Do your other thing
        }
      } catch (err) {
        res.send({err: 'Something went terribly wrong'})
      }
    

    【讨论】:

      【解决方案3】:

      我认为您指的是进行查询。 仍然无法检查 Firestore 中是否存在某些字段。但是您可以添加另一个值为 true/false

      的字段
      val query = refUsersCollection
              .whereEqualTo("hasLocation", true)
      query.get().addOnSuccessListener { 
            // use the result
        }
      

      查看此链接了解更多信息

      https://firebase.google.com/docs/firestore/query-data/queries How do I get documents where a specific field exists/does not exists in Firebase Cloud Firestore?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多