If I have a Firebase Firestore database which I have retrieved a DocumentSnapshot
for the document corresponding to the collection on the right and stored in a document
variable, then how could I retrieve the value in that DocumentSnapshot
at the field "username"? The field has a string value.
To order the documents by a specific value, use the orderBy method: firestore() . collection('Users') // Order results . orderBy('age', 'desc') .
A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).
To query Firestore database for document ID with JavaScript, we call the doc method. Then we call doc to get the entry from the books collection with ID 'fK3ddutEpD2qQqRMXNW5' . Finally, we call get to return the object with the given ID.
DocumentSnapshot has a method getString() which takes the name of a field and returns its value as a String.
String value = document.getString("username");
you can use get
method to get value of a field
String username = (String) document.get("username"); //if the field is String
Boolean b = (Boolean) document.get("isPublic"); //if the field is Boolean
Integer i = (Integer) document.get("age") //if the field is Integer
checkout the doc for DocumentSnapshot
You need to do a DocumentReference
to get the content in your document.
A simple one will be like this.
DocumentReference docRef = myDB.collection("users").document("username");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
Log.i("LOGGER","First "+document.getString("first"));
Log.i("LOGGER","Last "+document.getString("last"));
Log.i("LOGGER","Born "+document.getString("born"));
} else {
Log.d("LOGGER", "No such document");
}
} else {
Log.d("LOGGER", "get failed with ", task.getException());
}
}
});
The downside is that you need to know your document ID to get the field values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With