首页 > 解决方案 > 用于同时保存文档和集合的结构 Firestore 查询

问题描述

我想为每个用户保存一个产品列表,并使用 geofirestore 查找最近用户的产品列表。

但是我将我的画笔与 Firestore 查询混合在一起。

import firestore from '@react-native-firebase/firestore';
import * as geofirestore from 'geofirestore';
const firestoreApp = firestore();
const GeoFirestore = geofirestore.initializeApp(firestoreApp);
const geocollection = GeoFirestore.collection('PRODUCTS');
geocollection
     .doc(user.uid)
        .set({
          coordinates: new firestore.GeoPoint(
            productLocation.lat,
            productLocation.long,
          ),
        })
          .collection('USER_PRODUCTS')
            .add({
              name: productName,
              description: productDescription,
              price: productPrice,
              quantity: productQuantity,
              image: productImage.name,
              createdDate: new Date(),
          });

我只能使用用户 ID 和坐标设置第一个文档,但不能添加“USER_PRODUCTS”集合。

是否可以像这样链接,或者我必须进行两个不同的查询?

有人有更好的主意吗?

标签: javascriptreact-nativegoogle-cloud-firestoregeofirestore

解决方案


我的解决方案是提出两个不同的请求(一个使用 Geofirestore,一个使用 Firestore)。我猜想并希望有一个只有一个查询的解决方案,但目前该解决方案有效。

await geocollection.doc(user.uid).set({
        coordinates: new firestore.GeoPoint(
          productLocation.lat,
          productLocation.long,
        ),
      });

await firestore()
  .collection('PRODUCTS')
  .doc(user.uid)
  .collection('USER_PRODUCTS')
  .doc()
  .set(
    {
      name: productName,
      description: productDescription,
      price: productPrice,
      quantity: productQuantity,
      image: productImage.name,
      createdDate: new Date(),
    },
    {merge: true},
  );

推荐阅读