CollectionReference

CollectionReference

new CollectionReference()

A CollectionReference object can be used for adding documents, getting document references, and querying for documents (using the methods inherited from Query).

Extends

Members

firestore

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

Inherited From:
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 collection.

Example
```
let collectionRef = firestore.collection('col/doc/subcollection');
console.log(`ID of the subcollection: ${collectionRef.id}`);
```

parent

A reference to the containing Document if this is a subcollection, else null.

Example
```
let collectionRef = firestore.collection('col/doc/subcollection');
let documentRef = collectionRef.parent;
console.log(`Parent name: ${documentRef.path}`);
```

path

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

Example
```
let collectionRef = firestore.collection('col/doc/subcollection');
console.log(`Path of the subcollection: ${collectionRef.path}`);
```

Methods

add(data) → {Promise.<DocumentReference>}

Add a new document to this collection with the specified data, assigning it a document ID automatically.

Parameters:
Name Type Description
data DocumentData

An Object containing the data for the new document.

Returns:
Type Description
Promise.<DocumentReference>

A Promise resolved with a DocumentReference pointing to the newly created document.

Throws:

If the provided input is not a valid Firestore document.

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

aggregate(aggregateSpec)

Returns a query that can perform the given aggregations.

The returned query, when executed, calculates the specified aggregations over the documents in the result set of this query without actually downloading the documents.

Using the returned query to perform aggregations is efficient because only the final aggregation values, not the documents' data, is downloaded. The returned query can perform aggregations of the documents count the documents in cases where the result set is prohibitively large to download entirely (thousands of documents).

Parameters:
Name Type Description
aggregateSpec

An AggregateSpec object that specifies the aggregates to perform over the result set. The AggregateSpec specifies aliases for each aggregate, which can be used to retrieve the aggregate result.

Inherited From:
Example
```typescript
const aggregateQuery = col.aggregate(query, {
  countOfDocs: count(),
  totalHours: sum('hours'),
  averageScore: average('score')
});

const aggregateSnapshot = await aggregateQuery.get();
const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
const totalHours: number = aggregateSnapshot.data().totalHours;
const averageScore: number | null = aggregateSnapshot.data().averageScore;
```

count()

Returns a query that counts the documents in the result set of this query.

The returned query, when executed, counts the documents in the result set of this query without actually downloading the documents.

Using the returned query to count the documents is efficient because only the final count, not the documents' data, is downloaded. The returned query can count the documents in cases where the result set is prohibitively large to download entirely (thousands of documents).

Returns:
Type Description

a query that counts the documents in the result set of this query. The count can be retrieved from snapshot.data().count, where snapshot is the AggregateQuerySnapshot resulting from running the returned query.

Inherited From:

doc(documentPathopt) → {DocumentReference}

Gets a DocumentReference instance that refers to the document at the specified path. If no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference.

Parameters:
Name Type Attributes Description
documentPath string <optional>

A slash-separated path to a document.

Returns:
Type Description
DocumentReference

The DocumentReference instance.

Example
```
let collectionRef = firestore.collection('col');
let documentRefWithName = collectionRef.doc('doc');
let documentRefWithAutoId = collectionRef.doc();
console.log(`Reference with name: ${documentRefWithName.path}`);
console.log(`Reference with auto-id: ${documentRefWithAutoId.path}`);
```

endAt(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that ends at the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should end at or the field values to end this query at, in order of the query's order by.

Returns:
Type Description
Query

A query with the new ending point.

Inherited From:
Example
```
let query = firestore.collection('col');

query.orderBy('foo').endAt(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

endBefore(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that ends before the set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should end before or the field values to end this query before, in order of the query's order by.

Returns:
Type Description
Query

A query with the new ending point.

Inherited From:
Example
```
let query = firestore.collection('col');

query.orderBy('foo').endBefore(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

(async) explain()

Plans and optionally executes this query. Returns a Promise that will be resolved with the planner information, statistics from the query execution (if any), and the query results (if any).

Returns:
Type Description

A Promise that will be resolved with the planner information, statistics from the query execution (if any), and the query results (if any).

Inherited From:

explainStream()

Executes the query and streams the results as the following object: {document?: DocumentSnapshot, metrics?: ExplainMetrics}

The stream surfaces documents one at a time as they are received from the server, and at the end, it will surface the metrics associated with executing the query.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

let count = 0;

query.explainStream({analyze: true}).on('data', (data) => {
  if (data.document) {
    // Use data.document which is a DocumentSnapshot instance.
    console.log(`Found document with name '${data.document.id}'`);
    ++count;
  }
  if (data.metrics) {
    // Use data.metrics which is an ExplainMetrics instance.
  }
}).on('end', () => {
  console.log(`Received ${count} documents.`);
});
```

(async) get() → {Promise.<QuerySnapshot>}

Executes the query and returns the results as a QuerySnapshot.

Returns:
Type Description
Promise.<QuerySnapshot>

A Promise that resolves with the results of the Query.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

query.get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

getInequalityFilterFields()

Returns the sorted array of inequality filter fields used in this query.

Returns:
Type Description

An array of inequality filter fields sorted lexicographically by FieldPath.

Inherited From:

isEqual(other) → {boolean}

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

Parameters:
Name Type Description
other *

The value to compare against.

Returns:
Type Description
boolean

true if this CollectionReference is equal to the provided value.

Overrides:

limit(limit) → {Query}

Creates and returns a new Query that only returns the first matching documents.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the limit.

Parameters:
Name Type Description
limit number

The maximum number of items to return.

Returns:
Type Description
Query

The created Query.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.limit(1).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

limitToLast(limit)

Creates and returns a new Query that only returns the last matching documents.

You must specify at least one orderBy clause for limitToLast queries, otherwise an exception will be thrown during execution.

Results for limitToLast queries cannot be streamed via the stream() API.

Parameters:
Name Type Description
limit

The maximum number of items to return.

Returns:
Type Description

The created Query.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.limitToLast(1).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Last matching document is ${documentSnapshot.ref.path}`);
  });
});
```

listDocuments() → {Promise.<Array.<DocumentReference>>}

Retrieves the list of documents in this collection.

The document references returned may include references to "missing documents", i.e. document locations that have no document present but which contain subcollections with documents. Attempting to read such a document reference (e.g. via .get() or .onSnapshot()) will return a DocumentSnapshot whose .exists property is false.

Returns:
Type Description
Promise.<Array.<DocumentReference>>

The list of documents in this collection.

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

return collectionRef.listDocuments().then(documentRefs => {
   return firestore.getAll(...documentRefs);
}).then(documentSnapshots => {
   for (let documentSnapshot of documentSnapshots) {
      if (documentSnapshot.exists) {
        console.log(`Found document with data: ${documentSnapshot.id}`);
      } else {
        console.log(`Found missing document: ${documentSnapshot.id}`);
      }
   }
});
```

offset(offset) → {Query}

Specifies the offset of the returned results.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the offset.

Parameters:
Name Type Description
offset number

The offset to apply to the Query results

Returns:
Type Description
Query

The created Query.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.limit(10).offset(20).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

onSnapshot(onNext, onErroropt) → {function}

Attaches a listener for QuerySnapshot events.

Parameters:
Name Type Attributes Description
onNext querySnapshotCallback

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

onError errorCallback <optional>

A callback to be called if the listen fails or is cancelled. No further callbacks will occur.

Returns:
Type Description
function

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

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

let unsubscribe = query.onSnapshot(querySnapshot => {
  console.log(`Received query snapshot of size ${querySnapshot.size}`);
}, err => {
  console.log(`Encountered error: ${err}`);
});

// Remove this listener.
unsubscribe();
```

orderBy(fieldPath, directionStropt) → {Query}

Creates and returns a new Query that's additionally sorted by the specified field, optionally in descending order instead of ascending.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the field mask.

Parameters:
Name Type Attributes Description
fieldPath string | FieldPath

The field to sort by.

directionStr string <optional>

Optional direction to sort by ('asc' or 'desc'). If not specified, order will be ascending.

Returns:
Type Description
Query

The created Query.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.orderBy('foo', 'desc').get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

select(…fieldPaths) → {Query}

Creates and returns a new Query instance that applies a field mask to the result and returns only the specified subset of fields. You can specify a list of field paths to return, or use an empty list to only return the references of matching documents.

Queries that contain field masks cannot be listened to via onSnapshot() listeners.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the field mask.

Parameters:
Name Type Attributes Description
fieldPaths string | FieldPath <repeatable>

The field paths to return.

Returns:
Type Description
Query

The created Query.

Inherited From:
Example
```
let collectionRef = firestore.collection('col');
let documentRef = collectionRef.doc('doc');

return documentRef.set({x:10, y:5}).then(() => {
  return collectionRef.where('x', '>', 5).select('y').get();
}).then((res) => {
  console.log(`y is ${res.docs[0].get('y')}.`);
});
```

startAfter(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that starts after the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should start after or the field values to start this query after, in order of the query's order by.

Returns:
Type Description
Query

A query with the new starting point.

Inherited From:
Example
```
let query = firestore.collection('col');

query.orderBy('foo').startAfter(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

startAt(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that starts at the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should start at or the field values to start this query at, in order of the query's order by.

Returns:
Type Description
Query

A query with the new starting point.

Inherited From:
Example
```
let query = firestore.collection('col');

query.orderBy('foo').startAt(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

stream() → {Stream.<QueryDocumentSnapshot>}

Executes the query and streams the results as QueryDocumentSnapshots.

Returns:
Type Description
Stream.<QueryDocumentSnapshot>

A stream of QueryDocumentSnapshots.

Inherited From:
Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

let count = 0;

query.stream().on('data', (documentSnapshot) => {
  console.log(`Found document with name '${documentSnapshot.id}'`);
  ++count;
}).on('end', () => {
  console.log(`Total count is ${count}`);
});
```

withConverter(converter)

Applies a custom data converter to this CollectionReference, allowing you to use your own custom model objects with Firestore. When you call add() on the returned CollectionReference 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:
Name Type Description
converter FirestoreDataConverter | null

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

Returns:
Type Description

A CollectionReference that uses the provided converter.

Overrides:
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
}

```