DocumentSnapshot
A DocumentSnapshot is an immutable representation for a document in a Firestore database. The data can be extracted with data() or get(fieldPath) to get a specific field.
The snapshot can point to a non-existing document in which case exists will return false. Calling data() or get(fieldPath) for such a document throws an error.
Properties
createTime
string
The time the document was created. Undefined for documents that don't exist.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then((documentSnapshot) => {
if (documentSnapshot.exists) {
console.log(`Document created at '${documentSnapshot.createTime}'`);
}
});
exists
boolean
True if the document exists.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then((documentSnapshot) => {
if (documentSnapshot.exists) {
console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`);
}
});
id
string
The ID of the document for which this DocumentSnapshot contains data.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then((documentSnapshot) => {
if (documentSnapshot.exists) {
console.log(`Document found with name '${documentSnapshot.id}'`);
}
});
readTime
string
The time this snapshot was read.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then((documentSnapshot) => {
console.log(`Document read at '${documentSnapshot.readTime}'`);
});
ref
A DocumentReference for the document stored in this snapshot.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then((documentSnapshot) => {
if (documentSnapshot.exists) {
console.log(`Found document at '${documentSnapshot.ref.path}'`);
}
});
updateTime
string
The time the document was last updated (at the time the snapshot was generated). Undefined for documents that don't exist.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then((documentSnapshot) => {
if (documentSnapshot.exists) {
console.log(`Document updated at '${documentSnapshot.updateTime}'`);
}
});
Methods
data
data() returns DocumentData
Retrieves all fields in the document as an object.
- Returns
-
An object containing all fields in the document.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then(documentSnapshot => {
let data = documentSnapshot.data();
console.log(`Retrieved data: ${JSON.stringify(data)}`);
});
get
get(field) returns any type
Retrieves the field specified by fieldPath
.
Parameter |
|
---|---|
field |
(string or FieldPath) The field path (e.g. 'foo' or 'foo.bar') to a specific field. |
- Returns
-
any type
The data at the specified field location or undefined if no such field exists.
Example
let documentRef = firestore.doc('col/doc');
documentRef.set({ a: { b: 'c' }}).then(() => {
return documentRef.get();
}).then(documentSnapshot => {
let field = documentSnapshot.get('a.b');
console.log(`Retrieved field value: ${field}`);
});