MichaelSolati / geofirestore-js

Location-based querying and filtering using Firebase Firestore.
https://geofirestore.com
MIT License
505 stars 58 forks source link

How to update a document #45

Closed 24dev closed 6 years ago

24dev commented 6 years ago

Loving the library so far, just having one issue!

After using .add(), the document appears correctly in the database. On .then, the docRef is also correct. However, using .set() on the document does not seem to work - the id is not being added to the document. I may be using it incorrectly, so have attached my code.

const restaurantsGeostoreRef = db.collection('exploreMap');
const restaurantsRef = new GeoFirestore(restaurantsGeostoreRef);
export const addNewRestaurant = data =>
  restaurantsRef
    .add({
      ...data,
      coordinates: new firebase.firestore.GeoPoint(data.coordinates[1], data.coordinates[0]),
    })
    .then(docRef =>
      restaurantsRef
        .set(docRef.id, {
          id: docRef.id,
        })
        .then(() => 'Successfully added.')
        .catch(error => error),
    )
    .catch(error => error);
MichaelSolati commented 6 years ago

The set function requires a full document, so the original with modifications, not just the modifications (as it looks for coordinates). So you'll want something like this:

const restaurantsGeostoreRef = db.collection('exploreMap');
const restaurantsRef = new GeoFirestore(restaurantsGeostoreRef);

export const addNewRestaurant = (data) => {
    const doc = {
        ...data,
        coordinates: new firebase.firestore.GeoPoint(data.coordinates[1], data.coordinates[0]),
    };

    restaurantsRef.add(doc)
        .then(docRef => restaurantsRef.set(docRef.id, { id: docRef.id, ...doc })
            .then(() => 'Successfully added.')
            .catch(error => error)
        ).catch(error => error);
}
24dev commented 6 years ago

Works, appreciate it!

AndrewAi commented 6 years ago

Can I still use firestore's set method, or would it be better to using geofirestores implementation of the set method? similarly with the remove method, if I just remove the document, it will just be deleted but all the other won't be affected. Thank you for the library, its brilliant so far!

MichaelSolati commented 6 years ago

@AndrewAi I would advise you to use the libraries set method, as it has to parse your document for changes/adjustments. However for remove it wont matter.