Members
SERVICE
Span names for instrumented operations.
Methods
and(first, second, …more)
Creates an expression that performs a logical 'AND' operation on multiple filter conditions.
// Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND
// the 'status' field is "active"
const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active"));
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
first |
The first filter condition. |
||
second |
The second filter condition. |
||
more |
<repeatable> |
Additional filter conditions to 'AND' together. |
Returns:
| Type | Description |
|---|---|
|
A new |
array(elements)
Creates an expression that creates a Firestore array value from an input array.
// Create an array value from the input array and reference the 'baz' field value from the input document.
array(['bar', field('baz')]).as('foo');
Parameters:
| Name | Type | Description |
|---|---|---|
elements |
The input array to evaluate in the expression. |
Returns:
| Type | Description |
|---|---|
|
A new |
conditional(condition, thenExpr, elseExpr)
Creates a conditional expression that evaluates to a 'then' expression if a condition is true and an 'else' expression if the condition is false.
// If 'age' is greater than 18, return "Adult"; otherwise, return "Minor".
conditional(
greaterThan("age", 18), constant("Adult"), constant("Minor"));
Parameters:
| Name | Type | Description |
|---|---|---|
condition |
The condition to evaluate. |
|
thenExpr |
The expression to evaluate if the condition is true. |
|
elseExpr |
The expression to evaluate if the condition is false. |
Returns:
| Type | Description |
|---|---|
|
A new |
countAll()
Creates an aggregation that counts the total number of stage inputs.
// Count the total number of input documents
countAll().as("totalDocument");
Returns:
| Type | Description |
|---|---|
|
A new |
countDistinct(expr)
Creates an aggregation that counts the number of distinct values of a field.
Parameters:
| Name | Type | Description |
|---|---|---|
expr |
The expression or field to count distinct values of. |
Returns:
| Type | Description |
|---|---|
|
A new |
countIf(booleanExpr)
Creates an aggregation that counts the number of stage inputs where the provided boolean expression evaluates to true.
// Count the number of documents where 'is_active' field equals true
countIf(field("is_active").equal(true)).as("numActiveDocuments");
Parameters:
| Name | Type | Description |
|---|---|---|
booleanExpr |
The boolean expression to evaluate on each input. |
Returns:
| Type | Description |
|---|---|
|
A new |
currentDocument()
Creates an expression that represents the current document being processed.
Returns:
| Type | Description |
|---|---|
|
An |
Example
```typescript
// Define the current document as a variable "doc"
firestore.pipeline().collection("books")
.define(currentDocument().as("doc"))
// Access a field from the defined document variable
.select(variable("doc").getField("title"));
```
currentTimestamp()
Creates an expression that evaluates to the current server timestamp.
// Get the current server timestamp
currentTimestamp()
Returns:
| Type | Description |
|---|---|
|
A new Expression representing the current server timestamp. |
detectMapRepresentation(mapValue)
Detects the 'valueType' for cases where a map value has been used to represent another type.
Parameters:
| Name | Type | Description |
|---|---|---|
mapValue |
The map value to probe. |
documentMatches(rquery)
Parameters:
| Name | Type | Description |
|---|---|---|
rquery |
Define the search query using the search domain-specific language (DSL). |
Returns:
| Type | Description |
|---|---|
|
A |
field(field)
Creates a Field instance representing the field at the given path.
The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field (e.g., "address.city").
// Create a Field instance for the 'title' field
const titleField = field("title");
// Create a Field instance for a nested field 'author.firstName'
const authorFirstNameField = field("author.firstName");
Parameters:
| Name | Type | Description |
|---|---|---|
field |
The path to the field. |
Returns:
| Type | Description |
|---|---|
|
A new |
geoDistance(fieldName, location)
Parameters:
| Name | Type | Description |
|---|---|---|
fieldName |
Specifies the field in the document which contains the first GeoPoint for distance computation. |
|
location |
Compute distance to this GeoPoint. |
Returns:
| Type | Description |
|---|---|
|
An |
isError(value)
Creates an expression that checks if a given expression produces an error.
// Check if the result of a calculation is an error
isError(field("title").arrayContains(1));
Parameters:
| Name | Type | Description |
|---|---|---|
value |
The expression to check. |
Returns:
| Type | Description |
|---|---|
|
A new |
isMapValue()
Returns true if value is a MapValue.
isTemporalInstant()
Checks if the given value is an instance of Temporal.Instant.
Checks both instanceof against runtime Temporal.Instant (if available)
and duck typing via [Symbol.toStringTag] and epochNanoseconds bigint property
to support polyfills or cross-realm instances.
map(elements)
Creates an expression that creates a Firestore map value from an input object.
// Create a map from the input object and reference the 'baz' field value from the input document.
map({foo: 'bar', baz: field('baz')}).as('data');
Parameters:
| Name | Type | Description |
|---|---|---|
elements |
The input map to evaluate in the expression. |
Returns:
| Type | Description |
|---|---|
|
A new |
nor(first, second, …more)
Creates an expression that performs a logical 'NOR' operation on multiple filter conditions.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
first |
The first filter condition. |
||
second |
The second filter condition. |
||
more |
<repeatable> |
Additional filter conditions to 'NOR' together. |
Returns:
| Type | Description |
|---|---|
|
A new |
Example
```typescript
// Check if neither the 'age' field is greater than 18 nor the 'city' field is "London"
const condition = nor(
greaterThan("age", 18),
equal("city", "London")
);
```
not(booleanExpr)
Creates an expression that negates a filter condition.
// Find documents where the 'completed' field is NOT true
not(equal("completed", true));
Parameters:
| Name | Type | Description |
|---|---|---|
booleanExpr |
The filter condition to negate. |
Returns:
| Type | Description |
|---|---|
|
A new |
or(first, second, …more)
Creates an expression that performs a logical 'OR' operation on multiple filter conditions.
// Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR
// the 'status' field is "active"
const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active"));
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
first |
The first filter condition. |
||
second |
The second filter condition. |
||
more |
<repeatable> |
Additional filter conditions to 'OR' together. |
Returns:
| Type | Description |
|---|---|
|
A new |
pipelineValue()
rand()
Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0.
Returns:
| Type | Description |
|---|---|
|
A new |
score()
Returns:
| Type | Description |
|---|---|
|
An |
selectablesToMap()
setLogFunction(logger)
Sets or disables the log function for all active Firestore instances.
Parameters:
| Name | Type | Description |
|---|---|---|
logger |
A log function that takes a message (such as |
switchOn(condition, result, …others)
Creates an expression that evaluates to the result corresponding to the first true condition.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
condition |
The first condition to check. |
||
result |
The result if the first condition is true. |
||
others |
<repeatable> |
Additional conditions and results, and optionally a default value. |
Returns:
| Type | Description |
|---|---|
|
A new |
Example
```typescript
// Return "Active" if field "status" is 1, "Pending" if field "status" is 2,
// and default to "Unknown" if none of the conditions are true.
switchOn(
equal(field("status"), 1), constant("Active"),
equal(field("status"), 2), constant("Pending"),
constant("Unknown")
)
```
validateUserDataHelper()
variable(name)
Creates an expression that retrieves the value of a variable bound via define().
Parameters:
| Name | Type | Description |
|---|---|---|
name |
The name of the variable to retrieve. |
Returns:
| Type | Description |
|---|---|
|
An |
Example
```typescript
db.pipeline().collection("products")
.define(
field("price").multiply(0.9).as("discountedPrice"),
field("stock").add(10).as("newStock")
)
.where(variable("discountedPrice").lessThan(100))
.select(field("name"), variable("newStock"));
```
xor(first, second, …additionalConditions)
Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExprs.
// Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London",
// or 'status' is "active".
const condition = xor(
greaterThan("age", 18),
equal("city", "London"),
equal("status", "active"));
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
first |
The first condition. |
||
second |
The second condition. |
||
additionalConditions |
<repeatable> |
Additional conditions to 'XOR' together. |
Returns:
| Type | Description |
|---|---|
|
A new |
Type Definitions
BulkWriterError
An error thrown when a BulkWriter operation fails.
The error used by BulkWriter~shouldRetryCallback set in BulkWriter#onWriteError.
Properties:
| Name | Type | Description |
|---|---|---|
code |
GrpcStatus |
The status code of the error. |
message |
string |
The error message of the error. |
documentRef |
DocumentReference |
The document reference the operation was performed on. |
operationType |
'create' | 'set' | 'update' | 'delete' |
The type of operation performed. |
failedAttempts |
number |
How many times this operation has been attempted unsuccessfully. |
BulkWriterOptions
An options object to configure throttling on BulkWriter.
Whether to disable or configure throttling. By default, throttling is
enabled. throttling can be set to either a boolean or a config object.
Setting it to true will use default values. You can override the defaults
by setting it to false to disable throttling, or by setting the config
values to enable throttling with the provided values.
Properties:
| Name | Type | Description |
|---|---|---|
throttling |
boolean | Object |
Whether to disable or enable
throttling. Throttling is enabled by default, if the field is set to |
DocumentData
Document data (e.g. for use with set()) consisting of fields mapped to values.
FirestoreDataConverter
Converter used by withConverter() to transform
user objects of type AppModelType into Firestore data of type
DbModelType.
Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.
Properties:
| Name | Type | Description |
|---|---|---|
toFirestore |
function |
Called by the Firestore SDK to convert a
custom model object of type |
fromFirestore |
function |
Called by the Firestore SDK to convert
Firestore data into an object of type |
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
}
```
GrpcStatus
Status codes returned by GRPC operations.
Precondition
An options object that configures conditional behavior of update() and delete() calls in DocumentReference, WriteBatch, BulkWriter, and Transaction. Using Preconditions, these calls can be restricted to only apply to documents that match the specified conditions.
Properties:
| Name | Type | Description |
|---|---|---|
lastUpdateTime |
Timestamp |
The update time to enforce. If set, enforces that the document was last updated at lastUpdateTime. Fails the operation if the document was last updated at a different time. |
exists |
boolean |
If set, enforces that the target document must or must not exist. |
Example
```
const documentRef = firestore.doc('coll/doc');
documentRef.get().then(snapshot => {
const updateTime = snapshot.updateTime;
console.log(`Deleting document at update time: ${updateTime.toDate()}`);
return documentRef.delete({ lastUpdateTime: updateTime });
});
```
ReadOptions
An options object that can be used to configure the behavior of
getAll() calls. By providing a fieldMask, these
calls can be configured to only return a subset of fields.
Properties:
| Name | Type | Description |
|---|---|---|
fieldMask |
Array.<(string|FieldPath)> |
Specifies the set of fields to return and reduces the amount of data transmitted by the backend. Adding a field mask does not filter results. Documents do not need to contain values for all the fields in the mask to be part of the result set. |
SetOptions
An options object that configures the behavior of set() calls in DocumentReference, WriteBatch, and Transaction. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions object with { merge : true }.
Properties:
| Name | Type | Description |
|---|---|---|
merge |
boolean |
Changes the behavior of a set() call to only replace the values specified in its data argument. Fields omitted from the set() call remain untouched. |
mergeFields |
Array.<(string|FieldPath)> |
Changes the behavior of set() calls to only replace the specified field paths. Any field path that is not specified is ignored and remains untouched. It is an error to pass a SetOptions object to a set() call that is missing a value for any of the fields specified here. |
UpdateData
Update data (for use with update) that contains paths mapped to values. Fields that contain dots reference nested fields within the document.
You can update a top-level field in your document by using the field name
as a key (e.g. foo). The provided value completely replaces the contents
for this field.
You can also update a nested field directly by using its field path as a key
(e.g. foo.bar). This nested field update replaces the contents at bar
but does not modify other data under foo.
Example
```
const documentRef = firestore.doc('coll/doc');
documentRef.set({a1: {a2: 'val'}, b1: {b2: 'val'}, c1: {c2: 'val'}});
documentRef.update({
b1: {b3: 'val'},
'c1.c3': 'val',
});
// Value is {a1: {a2: 'val'}, b1: {b3: 'val'}, c1: {c2: 'val', c3: 'val'}}
```
documentSnapshotCallback(snapshot)
onSnapshot() callback that receives a DocumentSnapshot.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot |
DocumentSnapshot |
A document snapshot. |
errorCallback(err)
onSnapshot() callback that receives an error.
Parameters:
| Name | Type | Description |
|---|---|---|
err |
Error |
An error from a listen. |
querySnapshotCallback(snapshot)
onSnapshot() callback that receives a QuerySnapshot.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot |
QuerySnapshot |
A query snapshot. |