DocumentReference

DocumentReference

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.

Constructor

new DocumentReference(_firestore, _path)

Parameters:
Name Type Description
_firestore

The Firestore Database client.

_path

The Path of this reference.

Source:

Members

(readonly) firestore :Firestore

The Firestore instance for the Firestore database (useful for performing transactions, etc.).

Source:
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}`);
});

(readonly) id :string

The last path element of the referenced document.

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

collectionRef.add({foo: 'bar'}).then(documentReference => {
  console.log(`Added document with name '${documentReference.id}'`);
});

(readonly) parent :CollectionReference

A reference to the collection to which this DocumentReference belongs.

Source:
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`);
}):

(readonly) path :string

A string representing the path of the referenced document (relative to the root of the database).

Source:
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.

Parameters:
Name Type Description
collectionPath string

A slash-separated path to a collection.

Source:
Example
let documentRef = firestore.doc('col/doc');
let subcollection = documentRef.collection('subcollection');
console.log(`Path to subcollection: ${subcollection.path}`);

create(data) → {Promise.<WriteResult>}

Create a document with the provided object values. This will fail the write if a document exists at its location.

Parameters:
Name Type Description
data DocumentData

An object that contains the fields and data to serialize as the document.

Source:
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}`);
});

delete(preconditionopt) → {Promise.<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).

Parameters:
Name Type Attributes Description
precondition Precondition <optional>

A precondition to enforce for this delete.

Properties
Name Type Attributes Description
lastUpdateTime Timestamp <optional>

If set, enforces that the document was last updated at lastUpdateTime. Fails the delete if the document was last updated at a different time.

Source:
Example
let documentRef = firestore.doc('col/doc');

documentRef.delete().then(() => {
  console.log('Document successfully deleted.');
});

get() → {Promise.<DocumentSnapshot>}

Reads the document referred to by this DocumentReference.

Source:
Example
let documentRef = firestore.doc('col/doc');

documentRef.get().then(documentSnapshot => {
  if (documentSnapshot.exists) {
    console.log('Document retrieved successfully.');
  }
});

isEqual(other) → {boolean}

Returns true if this DocumentReference is equal to the provided value.

Parameters:
Name Type Description
other *

The value to compare against.

Source:

listCollections() → {Promise.<Array.<CollectionReference>>}

Fetches the subcollections that are direct children of this document.

Source:
Example
let documentRef = firestore.doc('col/doc');

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

onSnapshot(onNext, onErroropt) → {function}

Attaches a listener for DocumentSnapshot events.

Parameters:
Name Type Attributes Description
onNext documentSnapshotCallback

A callback to be called every time a new DocumentSnapshot is available.

onError errorCallback <optional>

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.

Source:
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();

set(data, optionsopt) → {Promise.<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.

Parameters:
Name Type Attributes Description
data DocumentData

A map of the fields and values for the document.

options SetOptions <optional>

An object to configure the set behavior.

Properties
Name Type Attributes Description
merge boolean <optional>

If true, set() merges the values specified in its data argument. Fields omitted from this set() call remain untouched.

mergeFields Array.<(string|FieldPath)> <optional>

If provided, set() only replaces the specified field paths. Any field path that is not specified is ignored and remains untouched.

Source:
Example
let documentRef = firestore.doc('col/doc');

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

update(dataOrField, …preconditionOrValues) → {Promise.<WriteResult>}

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.

Parameters:
Name Type Attributes Description
dataOrField UpdateData | string | FieldPath

An object containing the fields and values with which to update the document or the path of the first field to update.

preconditionOrValues * | string | FieldPath | Precondition <repeatable>

An alternating list of field paths and values to update or a Precondition to restrict this update.

Source:
Example
let documentRef = firestore.doc('col/doc');

documentRef.update({foo: 'bar'}).then(res => {
  console.log(`Document updated at ${res.updateTime}`);
});