javascriptreact-nativegoogle-cloud-firestoregeofirestore

Structure firestore query for saving document and collection at the same time


I would like to save a list of products for each user and use geofirestore to find the product lists of the closest users.

But I mix my brushes with Firestore queries.

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(),
          });

I can only set the first doc with the user id and the coordinates, but cannot add the 'USER_PRODUCTS' collection.

Does it is possible to chain like that or I'll have to make two differents queries?

Someone have a better idea?


Solution

  • My solution was to make two different requests (one with Geofirestore and one with Firestore). I guess and hope that there is a solution with only one query, but for the moment this solution works.

    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},
      );