如何检查 geopoint 字段上的 firebase data() 是否存在空值

How do I check firebase data() for null values on a geopoint field

我正在添加用户地理点,我想在将数据推送到数组之前检查 snapShot.data().location.geopoint 是否为空,但我不断收到以下错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'geopoint' of undefined
TypeError: Cannot read property 'geopoint' of undefined
 

这是实际代码?

query.get()
            .then(list => {
              list.forEach(snapShot => {
                let userLat = (snapShot.data().location.geopoint.latitude > 0) ? snapShot.data().location.geopoint.latitude : 0;
                let userLong = (snapShot.data().location.geopoint.longitude > 0) ? snapShot.data().location.geopoint.longitude : 0;

                console.log('use lat long', userLat, userLong);

                let distance = this.geo.distance(this.geo.point(myLat, myLong), this.geo.point(userLat, userLong));
                if (distance <= this.userSettings.distance.upper) {
                  this.userInfo.push({
                    userId: snapShot.data().userId,
                    displayName: snapShot.data().displayName,
                  });
                }
              });
            })

我将如何检查 geopoint 中的空值,因为它抱怨我添加的实际空值检查:

            let userLat = (snapShot.data().location.geopoint.latitude > 0) ? snapShot.data().location.geopoint.latitude : 0;

您可以利用 snapshot.get(fieldPath) API (docs) 并执行:

let userLat = 0;
let userLong = 0;

if (snapShot.get("location.geopoint")) {
  userLat = snapShot.get("location.geopoint").latitude;
  userLong = snapShot.get("location.geopoint").longitude;
}