Retrieving a documents field value from Firestore

Asked
Active3 hr before
Viewed126 times

8 Answers

retrievingdocumentsfirestorevaluefield
90%

DocumentSnapshot has a method getString() which takes the name of a field and returns its value as a String.,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., You're probably getting a generic Object because the field doesn't have a String. Can you post a screenshot of your document in the Firestore console? – Rosário Pereira Fernandes Jan 29 '18 at 1:01 ,Connect and share knowledge within a single location that is structured and easy to search.

DocumentSnapshot has a method getString() which takes the name of a field and returns its value as a String.

String value = document.getString("username");
load more v
88%

//retrieve one document and save it to userDetails
const [userDetails, setUserDetails] = useState('')
db.collection('users').doc(id).get()
   .then(snapshot => setUserDetails(snapshot.data()))
72%

Cloud Firestore gives you the ability to read the value of a collection or a document. This can be a one-time read, or provided by realtime updates when the data within a query changes.,To learn more about all of the querying capabilities Cloud Firestore has to offer, view the Firebase documentation.,Cloud Firestore offers advanced capabilities for querying collections. Queries work with both one-time reads or subscribing to changes.,To read a collection or document once, call the Query.get or DocumentReference.get methods. In the below example a FutureBuilder is used to help manage the state of the request:

load more v
65%

An object containing the fields and values with which to update the document or the path of the first field to update.,An object that contains the fields and data to serialize as the document.,Reads the document referred to by this DocumentReference.,Deletes the document referred to by this DocumentReference.

Example
let collectionRef = firestore.collection('col');

collectionRef.add({
   foo: 'bar'
}).then(documentReference => {
   let firestore = documentReference.firestore;
   console.log(`Root location for document is ${firestore.formattedName}`);
});
Example
let collectionRef = firestore.collection('col');

collectionRef.add({
   foo: 'bar'
}).then(documentReference => {
   console.log(`Added document with name '${documentReference.id}'`);
});
Example
let documentRef = firestore.doc('col/doc');
let collectionRef = documentRef.parent;

collectionRef.where('foo', '==', 'bar').get().then(results => {
   console.log(`Found ${results.size} matches in parent collection`);
}):
Example
let collectionRef = firestore.collection('col');

collectionRef.add({
   foo: 'bar'
}).then(documentReference => {
   console.log(`Added document at '${documentReference.path}'`);
});
Example
let documentRef = firestore.doc('col/doc');
let subcollection = documentRef.collection('subcollection');
console.log(`Path to subcollection: ${subcollection.path}`);
Example
let documentRef = firestore.collection('col').doc();

documentRef.create({
   foo: 'bar'
}).then((res) => {
   console.log(`Document created at ${res.updateTime}`);
}).catch((err) => {
   console.log(`Failed to create document: ${err}`);
});
Example
let documentRef = firestore.doc('col/doc');

documentRef.delete().then(() => {
   console.log('Document successfully deleted.');
});
Example
let documentRef = firestore.doc('col/doc');

documentRef.get().then(documentSnapshot => {
   if (documentSnapshot.exists) {
      console.log('Document retrieved successfully.');
   }
});
Example
let documentRef = firestore.doc('col/doc');

documentRef.listCollections().then(collections => {
   for (let collection of collections) {
      console.log(`Found subcollection with id: ${collection.id}`);
   }
});
Example
let documentRef = firestore.doc('col/doc');

let unsubscribe = documentRef.onSnapshot(documentSnapshot => {
   if (documentSnapshot.exists) {
      console.log(documentSnapshot.data());
   }
}, err => {
   console.log(`Encountered error: ${err}`);
});

// Remove this listener.
unsubscribe();
Example
let documentRef = firestore.doc('col/doc');

documentRef.set({
   foo: 'bar'
}).then(res => {
   console.log(`Document written at ${res.updateTime}`);
});
Example
let documentRef = firestore.doc('col/doc');

documentRef.update({
   foo: 'bar'
}).then(res => {
   console.log(`Document updated at ${res.updateTime}`);
});
Example
class Post {
   constructor(readonly title: string, readonly author: string) {}

   toString(): string {
      return this.title + ', by ' + this.author;
   }
}

const postConverter = {
   toFirestore(post: Post): FirebaseFirestore.DocumentData {
      return {
         title: post.title,
         author: post.author
      };
   },
   fromFirestore(
      snapshot: FirebaseFirestore.QueryDocumentSnapshot
   ): Post {
      const data = snapshot.data();
      return new Post(data.title, data.author);
   }
};

const postSnap = await Firestore()
   .collection('posts')
   .withConverter(postConverter)
   .doc().get();
const post = postSnap.data();
if (post !== undefined) {
   post.title; // string
   post.toString(); // Should be defined
   post.someNonExistentProperty; // TS error
}
load more v
75%

Cloud Firestore provides the ability to read the value of a collection or document. This can be read one-time, or provide realtime updates when the data within a query changes.,This module requires that the @react-native-firebase/app module is already setup and installed. To install the "app" module, view the Getting Started documentation.,To learn more about all of the querying capabilities Cloud Firestore has to offer, view the Firebase documentation.,Cloud Firestore offers advanced capabilities for querying collections.

# Install & setup the app module
yarn add @react - native - firebase / app

# Install the firestore module
yarn add @react - native - firebase / firestore

# If you 're developing your app using iOS, run this command
cd ios / && pod install
load more v
40%

To delete a field inside the document, then you can use FieldValue.delete() with update():,In this article, we will add Cloud Firestore to a Flutter application, perform different read, write operation and use some queries to retrieve data.,To update fields inside a document, you can do the following:,To delete data from a document, you can use the method delete() which returns a Future<void>:

As I said before, to check how to create a flutter project and add the google-service.json file which is used for android, then please check this article How To Use Firebase In Flutter. Next, you need to add the following dependency to the pubspec.yaml file:

dependencies: cloud_firestore: ^ 0.14 .1 + 3
load more v
22%

Delete A Field From A Document on the Firestore Database,On each iteration, you will get value named doc, which is also a firebase query snapshot, that contains each user document with some additional metadata.,Get Documents Data from Firestore Database,Delete Data from Cloud Firestore

Let’s take a look at add() method sample code.

const db = firebase.firestore()
db.collection("users").add({
   name: "Anbu Selvan",
   email: "anbu.selvan@email.com",
   age: 25
})
load more v
60%

Example: get one document based on id in firestore

//retrieve one document and save it to userDetails
const [userDetails, setUserDetails] = useState('')
db.collection('users').doc(id).get()
   .then(snapshot => setUserDetails(snapshot.data()))

Other "retrieving-documents" queries related to "Retrieving a documents field value from Firestore"