Cloud Firestore Node.js Client Library

repository·main·Indexed 20 days ago

https://github.com/googleapis/nodejs-firestore

A Server SDK for interacting with Google Cloud Firestore, a NoSQL document database designed for high-throughput data management in trusted server environments. The library provides support for basic CRUD operations, advanced querying via Pipelines, aggregate queries using AggregateField and AggregateQuery, and high-throughput writes with BulkWriter. It also includes tools for creating data bundles with BundleBuilder and querying across collections with CollectionGroup.

Tokens
53.1K
Snippets
201
Records
236
Agent score
70%

What's inside @google-cloud/firestore

  1. Use Expression and Field for Firestore Pipelines

    main

    The @beta Firestore Pipelines API uses Expression and Field abstractions to build complex queries and data transformations.

    • Field: Represents a specific path in a document. You can create a field reference using the field() function.
    • Expression: An abstract base class for all pipeline operations. It provides a wide range of methods for mathematical, string, array, map, and timestamp manipulations, as well as boolean comparisons and aggregate functions.

    Note: These features are currently in beta.

    import { field } from '@google-cloud/firestore';
    
    // Example of creating a field reference
    const myField = field('some.nested.field');
  2. Use Pipeline expressions for array and aggregate operations

    main

    The Firestore Pipelines API (currently @beta) provides functional expressions for advanced querying and data manipulation.

    Array Operations:

    • arrayLength(array): Returns the length of an array.
    • arraySum(array): Returns the sum of elements in an array.
    • arrayMaximum(array) / arrayMinimum(array): Returns the max/min value.
    • arrayReverse(array): Reverses the array.
    • arrayMaximumN(array, n): Returns the top n maximum values.

    Aggregate & Ordering Operations:

    • average(expression): Calculates the average of a field or expression.
    • ascending(expr): Defines ascending order for a query.
    • byteLength(expr): Returns the byte length of a string or expression.
    • charLength(expr): Returns the character length of a string.
    • ceil(expr): Returns the ceiling of a numeric value.

    Boolean Expressions:

    • BooleanExpression objects support logical operations like .not() and conditional logic via .conditional(thenExpr, elseExpr) and .ifError(catchValue).
  3. Use beta expression functions for advanced queries

    main

    The library provides a set of @beta expression functions for complex data manipulation and filtering within queries. These functions typically return a BooleanExpression (for filtering) or a FunctionExpression (for transformation).

    String Operations:

    • startsWith(fieldName, prefix): Returns a BooleanExpression checking if a field starts with a prefix.
    • stringContains(fieldName, substring): Returns a BooleanExpression checking if a field contains a substring.
    • stringConcat(fieldName, ...strings): Returns a FunctionExpression to concatenate strings.
    • split(fieldName, delimiter): Returns a FunctionExpression to split a string.
    • reverse(expression): Returns a FunctionExpression to reverse a string.

    Regex Operations:

    • regexMatch(fieldName, pattern): Returns a BooleanExpression for regex matching.
    • regexContains(fieldName, pattern): Returns a BooleanExpression for regex containment.
    • regexFind(fieldName, pattern): Returns a FunctionExpression to find matches.
    • regexFindAll(fieldName, pattern): Returns a FunctionExpression to find all matches.

    Math and Numeric Operations:

    • round(fieldName, decimalPlaces): Returns a FunctionExpression to round a number.
    • sqrt(expression): Returns a FunctionExpression for square root.

    Other Operations:

    • rand(): Returns a FunctionExpression for random values.
    • rtrim(fieldName, valueToTrim): Returns a FunctionExpression to trim characters from the right.
  4. Perform string manipulations in Firestore Pipelines

    main

    The following @beta functions allow for string manipulation within Firestore Pipelines. These functions typically accept either a field name (string) or an Expression and return a FunctionExpression.

    Available string functions:

    • stringIndexOf(expression, search): Finds the index of a substring.
    • stringRepeat(fieldName | expression, repetitions): Repeats a string.
    • stringReplaceAll(fieldName | expression, find, replacement): Replaces all occurrences of a substring.
    • stringReplaceOne(fieldName | expression, find, replacement): Replaces only the first occurrence of a substring.
    • stringReverse(field | expression): Reverses the string.
    • substring(field | expression, position, length?): Extracts a portion of a string.
    • toLower(fieldName | expression): Converts string to lowercase.
    • toUpper(fieldName | expression): Converts string to uppercase.
  5. Manipulate and truncate timestamps in Firestore Pipelines

    main

    The following @beta functions allow for advanced timestamp operations within Firestore Pipelines.

    Timestamp Arithmetic:

    • timestampAdd(timestamp | fieldName, unit, amount): Adds a specified amount of time (unit: microsecond, millisecond, second, minute, hour, day) to a timestamp.
    • timestampSubtract(timestamp | fieldName, unit, amount): Subtracts a specified amount of time from a timestamp.

    Timestamp Conversion:

    • timestampToUnixMicros(expr | fieldName): Converts a timestamp to Unix microseconds.
    • timestampToUnixMillis(expr | fieldName): Converts a timestamp to Unix milliseconds.
    • timestampToUnixSeconds(expr | fieldName): Converts a timestamp to Unix seconds.

    Timestamp Truncation:

    • timestampTruncate(fieldName | expression, granularity, timezone?): Truncates a timestamp to a specific granularity (e.g., day, hour) and an optional timezone.
  6. Use Firestore Pipelines expressions and functions

    main

    The @beta Firestore Pipelines API provides a set of functions to build complex expressions for advanced querying and data manipulation. These functions are used to construct Expression objects.

    Mathematical & Logical Expressions:

    • constant(value): Creates a Constant expression from a value (number, string, boolean, null, Date, etc.).
    • concat(...others): Concatenates multiple expressions.
    • conditional(condition, thenExpr, elseExpr): Returns a conditional expression.
    • divide(dividend, divisor): Performs division between expressions.

    Aggregation Functions:

    • count(expression | fieldName | 'all'): Counts documents.
    • countDistinct(expr | string): Counts distinct values.
    • countIf(booleanExpr): Counts documents matching a condition.

    Vector & Similarity Search:

    • cosineDistance(fieldName | vectorExpression, vector | vectorExpression): Calculates cosine distance for vector similarity searches.

    Field & Identity Expressions:

    • collectionId(fieldName | expression): Returns the ID of the collection.
    • documentId(documentPath | expression): Returns the ID of a document.
    • currentTimestamp(): Returns the current server timestamp.
  7. Perform arithmetic and aggregation in Firestore Pipelines

    main

    Use these @beta functions to perform mathematical operations on numeric fields or expressions within Pipelines.

    Arithmetic functions:

    • subtract(minuend, subtrahend): Subtracts one value from another.

    Aggregation functions:

    • sum(expression | fieldName): Returns an AggregateFunction to calculate the sum of a field or expression.
  8. Quickstart: Basic CRUD operations with Firestore

    main

    This guide demonstrates how to initialize a Firestore client and perform basic Create, Read, Update, and Delete (CRUD) operations on a document.

    const {Firestore} = require('@google-cloud/firestore');
    
    // Create a new client
    const firestore = new Firestore();
    
    async function quickstart() {
      // Obtain a document reference.
      const document = firestore.doc('posts/intro-to-firestore');
    
      // Enter new data into the document.
      await document.set({
        title: 'Welcome to Firestore',
        body: 'Hello World',
      });
      console.log('Entered new data into the document');
    
      // Update an existing document.
      await document.update({
        body: 'My first Firestore app',
      });
      console.log('Updated an existing document');
    
      // Read the document.
      const doc = await document.get();
      console.log('Read the document');
    
      // Delete the document.
      await document.delete();
      console.log('Deleted the document');
    }
    quickstart();
  9. Install legacy versions of the Firestore client library

    main

    If you are using an end-of-life version of Node.js, you can install client libraries compatible with specific legacy versions using npm dist-tags. The naming convention is legacy-(version). For example, to install a version compatible with Node.js 8, use the tag legacy-8.

    npm install @google-cloud/firestore@legacy-8
  10. Configure raw options for stages and execution

    main

    Both PipelineExecuteOptions and StageOptions provide a rawOptions property. This is an escape hatch for passing options that are not yet supported by the SDK directly to the Firestore backend.

    • Format: Use a dictionary where keys are the backend option names (typically snake_case).
    • Precedence: Values in rawOptions take precedence over SDK-set options.
    • Nesting: Use dot notation to override nested properties without overwriting the entire object.

    Example: Overriding a nested option

    execute({
      pipeline: myPipeline,
      rawOptions: {
        "example_option.foo": "bar"
      }
    });