DocumentReference
Source: reference.
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.
Properties
firestore Firestore
The Firestore instance for the Firestore database (useful for performing transactions, etc.).
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}`);
});
id string
The last path element of the referenced document.
Example
let collectionRef = firestore.collection('col');
collectionRef.add({foo: 'bar'}).then(documentReference => {
console.log(`Added document with name '${documentReference.id}'`);
});
parent CollectionReference
A reference to the collection to which this DocumentReference belongs.
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`);
}):
path string
A string representing the path of the referenced document (relative to the root of the database).
Example
let collectionRef = firestore.collection('col');
collectionRef.add({foo: 'bar'}).then(documentReference => {
console.log(`Added document at '${documentReference.path}'`);
});
Methods
collection(collectionPath) → CollectionReference
Gets a CollectionReference instance that refers to the collection at the specified path.
Example
let documentRef = firestore.doc('col/doc');
let subcollection = documentRef.collection('subcollection');
console.log(`Path to subcollection: ${subcollection.path}`);
Parameter
| Name | Type | Optional | Description |
|---|---|---|---|
|
collectionPath |
string |
|
A slash-separated path to a collection. |
- Returns
-
A reference to the new subcollection.
create(data) → Promise containing WriteResult
Create a document with the provided object values. This will fail the write if a document exists at its location.
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}`);
});
Parameter
| Name | Type | Optional | Description |
|---|---|---|---|
|
data |
|
An object that contains the fields and data to serialize as the document. |
- Returns
-
Promise containing WriteResultA Promise that resolves with the write time of this create.
delete([precondition]) → Promise containing WriteResult
Deletes the document referred to by this DocumentReference.
A delete for a non-existing document is treated as a success (unless lastUptimeTime is provided).
Example
let documentRef = firestore.doc('col/doc');
documentRef.delete().then(() => {
console.log('Document successfully deleted.');
});
Parameters
| Name | Type | Optional | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
precondition |
Yes |
A precondition to enforce for this delete. Values in
|
- Returns
-
Promise containing WriteResultA Promise that resolves with the delete time.
get() → Promise containing DocumentSnapshot
Reads the document referred to by this DocumentReference.
Example
let documentRef = firestore.doc('col/doc');
documentRef.get().then(documentSnapshot => {
if (documentSnapshot.exists) {
console.log('Document retrieved successfully.');
}
});
- Returns
-
Promise containing DocumentSnapshotA Promise resolved with a DocumentSnapshot for the retrieved document on success. For missing documents, DocumentSnapshot.exists will be false. If the get() fails for other reasons, the Promise will be rejected.
isEqual(other) → boolean
Returns true if this DocumentReference is equal to the provided value.
Parameter
| Name | Type | Optional | Description |
|---|---|---|---|
|
other |
any type |
|
The value to compare against. |
- Returns
-
booleantrue if this
DocumentReferenceis equal to the provided value.
listCollections() → Promise containing Array of CollectionReference
Fetches the subcollections that are direct children of this document.
Example
let documentRef = firestore.doc('col/doc');
documentRef.listCollections().then(collections => {
for (let collection of collections) {
console.log(`Found subcollection with id: ${collection.id}`);
}
});
- Returns
-
Promise containing Array of CollectionReferenceA Promise that resolves with an array of CollectionReferences.
onSnapshot(onNext[, onError]) → function()
Attaches a listener for DocumentSnapshot events.
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();
Parameters
| Name | Type | Optional | Description |
|---|---|---|---|
|
onNext |
|
A callback to be called every
time a new |
|
|
onError |
Yes |
A callback to be called if the listen fails or is cancelled. No further callbacks will occur. If unset, errors will be logged to the console. |
- Returns
-
function()An unsubscribe function that can be called to cancel the snapshot listener.
set(data[, options]) → Promise containing WriteResult
Writes to the document referred to by this DocumentReference. If the document does not yet exist, it will be created. If you pass SetOptions, the provided data can be merged into an existing document.
Example
let documentRef = firestore.doc('col/doc');
documentRef.set({foo: 'bar'}).then(res => {
console.log(`Document written at ${res.updateTime}`);
});
Parameters
| Name | Type | Optional | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
data |
|
A map of the fields and values for the document. |
|||||||||||||
|
options |
Yes |
An object to configure the set behavior. Values in
|
- Returns
-
Promise containing WriteResultA Promise that resolves with the write time of this set.
update(dataOrField, ...preconditionOrValues)
Updates fields in the document referred to by this DocumentReference. If the document doesn't yet exist, the update fails and the returned Promise will be rejected.
The update() method accepts either an object with field paths encoded as keys and field values encoded as values, or a variable number of arguments that alternate between field paths and field values.
A Precondition restricting this update can be specified as the last argument.
Example
let documentRef = firestore.doc('col/doc');
documentRef.update({foo: 'bar'}).then(res => {
console.log(`Document updated at ${res.updateTime}`);
});
Parameters
| Name | Type | Optional | Description |
|---|---|---|---|
|
dataOrField |
(UpdateData, string, or FieldPath) |
|
An object containing the fields and values with which to update the document or the path of the first field to update. |
|
preconditionOrValues |
(any type, string, FieldPath, or Precondition) |
|
An alternating list of field paths and values to update or a Precondition to restrict this update. Value can be repeated. |
- Returns
-
Promise.
A Promise that resolves once the data has been successfully written to the backend.