firebase 使用JavaScript模块化语法查询Firestore中的Geohashes

9lowa7mx  于 2022-11-30  发布在  Java
关注(0)|答案(2)|浏览(113)

在阅读Firebase的geohashing文档时,我使用模块化SDK,并尝试转换名称空间代码,但遇到TypeError that q.get is not a function

// Find cities within Dkm of [lat, lng]
const center = [Number(lat), Number(lng)];
const radiusInM = dist * 1000;
// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geohashQueryBounds(center, radiusInM);
const promises = [];

for (const b of bounds) {
    const q = query(
    collection(db, USERS_COL),
    orderBy('geohash'),
    startAt(b[0]),
    endAt(b[1])
    );
    promises.push(q.get());
}

文档链接
文件代码:

st radiusInM = 50 * 1000;

// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geofire.geohashQueryBounds(center, radiusInM);
const promises = [];
for (const b of bounds) {
  const q = db.collection('cities')
    .orderBy('geohash')
    .startAt(b[0])
    .endAt(b[1]);

  promises.push(q.get());
}
gr8qqesn

gr8qqesn1#

我建议在进行这样的转换时将Firebase文档放在手边,因为它同时包含了旧语法和新语法的代码片段。
例如,有关执行查询的文档显示v9中的语法为:

getDocs(q)
yiytaume

yiytaume2#

附加代码,以防其他人也陷入此问题:我不得不完全删除get函数,使用getDoc(),保存快照数据,然后与中心进行比较,通过for循环

// Find cities within dist km of [lat, lng]
  const center = [Number(lat), Number(lng)];
  const radiusInM = dist * 1000;
  // Each item in 'bounds' represents a startAt/endAt pair. We have to issue
  // a separate query for each pair. There can be up to 9 pairs of bounds
  // depending on overlap, but in most cases there are 4.
  const bounds = geohashQueryBounds(center, radiusInM);
  const promises = [];

  for (const b of bounds) {
    const q = query(
      collection(db, USERS_COL),
      orderBy('geohash'),
      startAt(b[0]),
      endAt(b[1])
    );
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      promises.push(doc.data());
    });
  }

  var finalResult = [];
  // Collect all the query results together into a single list
  await Promise.all(promises)
    .then((snapshots) => {
      const matchingDocs = [];

      for (const snap of snapshots) {
        // We have to filter out a few false positives due to GeoHash
        // accuracy, but most will match
        const lat = snap.lat;
        const lng = snap.lng;
        const distanceInKm = distanceBetween([lat, lng], center);
        const distanceInM = distanceInKm * 1000;
        if (distanceInM <= radiusInM) {
          matchingDocs.push(snap);
        }
      }
      console.log('val', matchingDocs);
      return matchingDocs;
    })
    .then((matchingDocs) => {
      finalResult = matchingDocs;
      // return matchingDocs;
    });
  return finalResult;

相关问题