Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - Difference between QueryReferences and Snapshot?

What is the actual difference between QueryReference and Snapshot?. I am a little confused when using methods like get() and data(). To me, both seem to like returns the data from the store.

like image 732
Sathishkumar Rakkiyasamy Avatar asked Dec 22 '22 21:12

Sathishkumar Rakkiyasamy


2 Answers

A reference is just a description of a document (DocumentReference, a full path) or query (Query, against a collection, with filters) that could return documents. A snapshot is the container for the document(s) after the query completes successfully.

When you call get() on either a DocumentReference or Query, that asynchronously fetches documents, and the results will be delivered in the callback in the snapshot.

like image 183
Doug Stevenson Avatar answered Mar 15 '23 01:03

Doug Stevenson


Firestore returns us two types of objects: references and snapshots. Of these objects, they can be either Document or Collection versions. Firestore will always return us these objects, even if nothing exists at from that query.

A queryReference object is an object that represents the “current” place in the database that we are querying.

We get them by calling either:

firestore.doc(‘/users/:userId’);
firestore.collections(‘/users’); 

The queryReference object does not have the actual data of the collection or document. It instead has properties that tell us details about it, or the method to get the Snapshot object which gives us the data we are looking for.

We use documentRef objects to perform our CRUD methods (create, retrieve, update, delete). The documentRef methods are .set(), .get(), .update() and .delete() respectively.

We can also add documents to collections using the collectionRef object using the .add() method.

collectionRef.add({value: prop})

We get the snapshotObject from the referenceObject using the .get() method. ie.

documentRef.get() or collectionRef.get() 

documentRef returns a documentSnapshot object. collectionRef returns a querySnapshot object

Document Snapshot:

We get a documentSnapshot object from our documentReference object. The documentSnapshot object allows us to check if a document exists at this query using the .exists property which returns a boolean. We can also get the actual properties on the object by calling the .data() method, which returns us a JSON object of the document.

Query Snapshot

We get a querySnapshot object from our collectionReference object. We can check if there are any documents in the collection by calling the .empty property which returns a boolean. We can get all the documents in the collection by calling the .docs property. It returns an array of our documents as documentSnapshot objects.

like image 44
Yilmaz Avatar answered Mar 15 '23 02:03

Yilmaz