如何检查文档是否包含 Cloud Firestore 中的属性?

Dya*_*yan 10 node.js firebase google-cloud-firestore

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

Ale*_*amo 13

要解决这个问题,您可以简单地检查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);
    });
Run Code Online (Sandbox Code Playgroud)