DocumentReference

DocumentReference

new 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.

Members

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

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

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

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.

Parameters:
NameTypeDescription
collectionPathstring

A slash-separated path to a collection.

Returns:
TypeDescription
CollectionReference

A reference to the new subcollection.

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:
NameTypeDescription
dataDocumentData

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

Returns:
TypeDescription
Promise.<WriteResult>

A Promise that resolves with the write time of this create.

Throws:

If the provided input is not a valid Firestore document or if the document already exists.

Type
Error
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:
NameTypeAttributesDescription
preconditionPrecondition<optional>

A precondition to enforce for this delete.

Properties
NameTypeAttributesDescription
lastUpdateTimeTimestamp<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.

existsboolean<optional>

If set, enforces that the target document must or must not exist.

Returns:
TypeDescription
Promise.<WriteResult>

A Promise that resolves with the delete time.

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.

Returns:
TypeDescription
Promise.<DocumentSnapshot>

A 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.

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:
NameTypeDescription
other*

The value to compare against.

Returns:
TypeDescription
boolean

true if this DocumentReference is equal to the provided value.

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

Fetches the subcollections that are direct children of this document.

Returns:
TypeDescription
Promise.<Array.<CollectionReference>>

A Promise that resolves with an array of CollectionReferences.

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:
NameTypeAttributesDescription
onNextdocumentSnapshotCallback

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

onErrorerrorCallback<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.

Returns:
TypeDescription
function

An unsubscribe function that can be called to cancel the snapshot listener.

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:
NameTypeAttributesDescription
dataT | Partial.<AppModelType>

A map of the fields and values for the document.

optionsSetOptions<optional>

An object to configure the set behavior.

Properties
NameTypeAttributesDescription
mergeboolean<optional>

If true, set() merges the values specified in its data argument. Fields omitted from this set() call remain untouched. If your input sets any field to an empty map, all nested fields are overwritten.

mergeFieldsArray.<(string|FieldPath)><optional>

If provided, set() only replaces the specified field paths. Any field path that is not specified is ignored and remains untouched. If your input sets any field to an empty map, all nested fields are overwritten.

Returns:
TypeDescription
Promise.<WriteResult>

A Promise that resolves with the write time of this set.

Throws:

If the provided input is not a valid Firestore document.

Type
Error
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:
NameTypeAttributesDescription
dataOrFieldUpdateData | 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.

Returns:
TypeDescription
Promise.<WriteResult>

A Promise that resolves once the data has been successfully written to the backend.

Throws:

If the provided input is not valid Firestore data.

Type
Error
Example
```
let documentRef = firestore.doc('col/doc');

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

withConverter(converter)

Applies a custom data converter to this DocumentReference, allowing you to use your own custom model objects with Firestore. When you call set(), get(), etc. on the returned DocumentReference instance, the provided converter will convert between Firestore data of type NewDbModelType and your custom type NewAppModelType.

Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.

Passing in null as the converter parameter removes the current converter.

Parameters:
NameTypeDescription
converterFirestoreDataConverter | null

Converts objects to and from Firestore. Passing in null removes the current converter.

Returns:
TypeDescription

A DocumentReference that uses the provided converter.

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
}

```

x


Privacy · Terms