Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using a DocumentReference in Firestore and using just the id?

In Firestore you can create objects with data type Reference. But this is just the path to said document. What's the difference between using this and just using the id as a String field? Any advantages/disadvantages?

like image 985
camendoza94 Avatar asked Oct 24 '17 01:10

camendoza94


People also ask

What is DocumentReference firestore?

A DocumentReference refers to a document location in a Cloud Firestore database and can be used to write, read, or listen to the location. There may or may not exist a document at the referenced location. A DocumentReference can also be used to create a CollectionReference to a subcollection.

Can two documents have the same ID in firestore?

The firestore emulator is allowing two documents with the same ID to be added in a collection.

Is firestore document ID unique?

Correct, it is extremely unlikely, but not guaranteed.

What is the use of reference in firestore?

A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.


1 Answers

A Reference contains the entire path to a document, whereas a simple string ID has no context. Granted, you could just store the path as a string instead, but for convenience (and ease of use in custom objects) it can be useful to have the entire Reference object stored.

The sort order of a Reference is also different to that of a String. From the Supported Data Types documentation:

  • Reference sort order: By path elements (collection, document ID, collection, document ID...)
  • Text string sort order: UTF-8 encoded byte order

This means that you can also filter on a Reference object in the database by comparing it to another when writing queries.

For example:

var reference = db.collection("test").document("1");
var query = db.collection("test").orderBy("ref").where("ref", ">", reference);
like image 97
Grimthorr Avatar answered Nov 09 '22 21:11

Grimthorr