### Install Dependencies Source: https://github.com/googleapis/nodejs-firestore/blob/main/dev/CONTRIBUTING.md Run this command to install all necessary project dependencies before running tests or making code changes. ```bash npm install ``` -------------------------------- ### Install the Firestore client library Source: https://github.com/googleapis/nodejs-firestore/blob/main/README.md Use npm to install the Firestore package in your Node.js project. ```bash npm install @google-cloud/firestore ``` -------------------------------- ### GET /document/get Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Retrieves the document snapshot for the current reference. ```APIDOC ## GET /document/get ### Description Fetches the document snapshot from Firestore. ### Method GET ### Response #### Success Response (200) - **DocumentSnapshot** (Object) - The snapshot containing the document data. ``` -------------------------------- ### Perform CRUD operations with Firestore Source: https://github.com/googleapis/nodejs-firestore/blob/main/README.md Demonstrates initializing the Firestore client and performing set, update, get, and delete operations on a document. ```javascript 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(); ``` -------------------------------- ### Perform Document Operations (Set, Get, Update, Delete) Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Manage documents using set(), get(), update(), and delete() methods. Use FieldValue for server timestamps, increments, array unions, and deletions. Supports merge options and preconditions. ```javascript const {Firestore, FieldValue} = require('@google-cloud/firestore'); const firestore = new Firestore(); async function documentOperations() { // Get a document reference const docRef = firestore.doc('users/user123'); // Create or overwrite a document with set() await docRef.set({ name: 'Alice', email: 'alice@example.com', createdAt: FieldValue.serverTimestamp(), tags: ['developer', 'admin'] }); // Merge data into existing document (doesn't overwrite entire doc) await docRef.set({ lastLogin: FieldValue.serverTimestamp() }, { merge: true }); // Merge only specific fields await docRef.set({ name: 'Alice Smith', status: 'active' }, { mergeFields: ['name'] }); // Only 'name' is updated // Read a document const snapshot = await docRef.get(); if (snapshot.exists) { console.log('Document data:', snapshot.data()); console.log('Name field:', snapshot.get('name')); console.log('Created at:', snapshot.createTime.toDate()); } // Update specific fields (document must exist) await docRef.update({ 'profile.bio': 'Software engineer', // Nested field loginCount: FieldValue.increment(1), tags: FieldValue.arrayUnion('premium'), oldField: FieldValue.delete() }); // Update with precondition await docRef.update({status: 'inactive'}, { lastUpdateTime: snapshot.updateTime }); // Delete a document await docRef.delete(); // Delete with precondition (only if document exists) await docRef.delete({ exists: true }); } ``` -------------------------------- ### GET /transaction/get Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Retrieves a document or query result within the transaction. ```APIDOC ## GET /transaction/get ### Description Retrieves a document snapshot or query snapshot within the transaction. ### Method GET ### Parameters #### Query Parameters - **query/documentRef** (Query/DocumentReference) - Required - The query or document reference to fetch. ``` -------------------------------- ### Timestamp Function Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Function to get the current server timestamp. ```APIDOC ## Timestamp Function ### Description Returns the current server timestamp. ### Method - `currentTimestamp(): FunctionExpression` ``` -------------------------------- ### Array Access and Manipulation Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Functions for accessing, reversing, and getting the length of arrays. ```APIDOC ## arrayFirst ### Description Gets the first element of an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayFirst(arrayExpression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayFirstN ### Description Gets the first N elements of an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayFirstN(fieldName: string, n: number | Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayGet ### Description Gets an element from an array at a specific index. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayGet(arrayField: string, index: number | Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayIndexOf ### Description Finds the index of the first occurrence of a value in an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayIndexOf(fieldName: string, search: unknown | Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayIndexOfAll ### Description Finds the indices of all occurrences of a value in an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayIndexOfAll(fieldName: string, search: unknown | Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayLast ### Description Gets the last element of an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayLast(fieldName: string | arrayExpression: Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayLastIndexOf ### Description Finds the index of the last occurrence of a value in an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayLastIndexOf(fieldName: string, search: unknown | Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayLastN ### Description Gets the last N elements of an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayLastN(fieldName: string, n: number | Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayLength ### Description Gets the length of an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayLength(fieldName: string | array: Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ## arrayReverse ### Description Reverses the order of elements in an array. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "arrayReverse(fieldName: string | arrayExpression: Expression)" } ``` ### Response #### Success Response (200) - **FunctionExpression** (object) - A function expression representing the operation. #### Response Example ```json { "example": "FunctionExpression" } ``` ``` -------------------------------- ### Run Sample Integration Tests Source: https://github.com/googleapis/nodejs-firestore/blob/main/CONTRIBUTING.md Execute sample integration tests for the project. ```bash # Run sample integration tests. npm run samples-test ``` -------------------------------- ### Run Sample Integration Tests Source: https://github.com/googleapis/nodejs-firestore/blob/main/dev/CONTRIBUTING.md Run integration tests that specifically target the sample code provided within the repository. ```bash # Run sample integration tests. npm run samples-test ``` -------------------------------- ### GET /document/listCollections Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Lists all subcollections associated with this document reference. ```APIDOC ## GET /document/listCollections ### Description Retrieves a list of all subcollections under this document. ### Method GET ### Response #### Success Response (200) - **Array** (Array) - A list of subcollection references. ``` -------------------------------- ### Implement Pagination with Query Cursors Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Uses startAt, startAfter, and endBefore methods to paginate through large datasets efficiently, including using document snapshots as cursors. ```javascript const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); async function paginationWithCursors() { const citiesRef = firestore.collection('cities'); // Start at a specific field value const fromBoston = await citiesRef .orderBy('name') .startAt('Boston') .limit(10) .get(); // Start after a specific field value const afterBoston = await citiesRef .orderBy('name') .startAfter('Boston') .limit(10) .get(); // End before/at specific values const beforeMiami = await citiesRef .orderBy('name') .endBefore('Miami') .get(); // Paginate using document snapshots (most reliable method) const firstPage = await citiesRef .orderBy('population', 'desc') .limit(25) .get(); // Get cursor for next page const lastDoc = firstPage.docs[firstPage.docs.length - 1]; // Fetch next page starting after the last document const secondPage = await citiesRef .orderBy('population', 'desc') .startAfter(lastDoc) .limit(25) .get(); // Multiple orderBy fields with corresponding cursor values const multiFieldCursor = await citiesRef .orderBy('state') .orderBy('population', 'desc') .startAt('California', 1000000) .limit(10) .get(); } ``` -------------------------------- ### Execute a Firestore Pipeline query Source: https://github.com/googleapis/nodejs-firestore/blob/main/README.md Demonstrates how to initialize a Firestore client, add documents to a collection, and execute a pipeline query that filters, sorts, and transforms data. ```javascript const {Firestore} = require('@google-cloud/firestore'); // Require/import Pipelines from '@google-cloud/firestore/pipelines' const {field} = require('@google-cloud/firestore/pipelines'); // Create a new client const firestore = new Firestore({ projectId: 'firestore-sdk-nightly', databaseId: 'enterprise' }); async function pipelinesQuickstart() { // Obtain a collection reference. const collection = firestore.collection('books'); // Enter new documents into the document. await collection.add({ "title": "Whispers of the Cobalt Sea", "price": 12.99, "author": "Elara Vance", "yearPublished": 2023 }); await collection.add({ "title": "The Antigravity Cat's Guide to Napping", "price": 24.50, "author": "Mittens the IV", "yearPublished": 2026 }); console.log('Entered new documents into the collection.'); // Define a Pipeline query that selects books published this century, // orders them by price, and computes a discounted price (20% off). const pipeline = firestore.pipeline().collection('books') .where(field('yearPublished').greaterThanOrEqual(2000)) .sort(field('price').ascending()) .select('title', 'author', field('price').multiply(0.8).as('discountedPrice')); // Execute the pipeline const pipelineSnapshot = await pipeline.execute(); console.log('Executed the Pipeline.'); console.log('Results:'); pipelineSnapshot.results.forEach(pipelineResult=> { console.log(pipelineResult.data()); }); } pipelinesQuickstart(); ``` -------------------------------- ### Run Unit Tests Source: https://github.com/googleapis/nodejs-firestore/blob/main/CONTRIBUTING.md Execute unit tests for the project. ```bash # Run unit tests. npm test ``` -------------------------------- ### Firestore Client Initialization Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Initializes a new Firestore client instance with optional settings. ```APIDOC ## Firestore Client Constructor ### Description Initializes a new Firestore client instance. Optional settings can be provided to configure the client. ### Method Constructor ### Parameters #### Request Body - **settings** (firestore.Settings) - Optional - Configuration settings for the Firestore client. ``` -------------------------------- ### Get Buffered Operations Count Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Retrieves the number of operations currently buffered by the BulkWriter. This is an internal method. ```typescript _getBufferedOperationsCount(): number; ``` -------------------------------- ### Initialize Firestore Client Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Initialize the Firestore client using Application Default Credentials or explicit configuration with project ID and key file. ```javascript const {Firestore} = require('@google-cloud/firestore'); // Using Application Default Credentials const firestore = new Firestore(); ``` ```javascript // With explicit configuration const firestoreWithConfig = new Firestore({ projectId: 'your-project-id', keyFilename: '/path/to/service-account.json', databaseId: 'my-database', // Optional: for named databases preferRest: true, // Optional: use HTTP/1.1 REST transport ignoreUndefinedProperties: true, // Optional: skip undefined values useBigInt: true // Optional: use BigInt for integers }); ``` -------------------------------- ### Run System Tests Source: https://github.com/googleapis/nodejs-firestore/blob/main/CONTRIBUTING.md Execute all system tests for the project. ```bash # Run all system tests. npm run system-test ``` -------------------------------- ### Query.explain Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Executes the query and returns the query plan and execution statistics. ```APIDOC ## explain ### Description Executes the query and returns the query plan and execution statistics. ### Parameters #### Request Body - **options** (firestore.ExplainOptions) - Optional - Configuration options for the explain operation. ### Response #### Success Response (200) - **result** (Promise>) - The query plan and execution results. ``` -------------------------------- ### Run System Tests Source: https://github.com/googleapis/nodejs-firestore/blob/main/dev/CONTRIBUTING.md Execute comprehensive system tests to ensure the library functions correctly within a complete environment. ```bash # Run all system tests. npm run system-test ``` -------------------------------- ### Run Unit Tests Source: https://github.com/googleapis/nodejs-firestore/blob/main/dev/CONTRIBUTING.md Execute unit tests to verify the correctness of individual code components. ```bash # Run unit tests. npm test ``` -------------------------------- ### Create Firestore Bundle Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Packages query results and documents into a bundle for offline use. Add named queries and individual documents to the bundle before building and saving it. ```javascript const {Firestore} = require('@google-cloud/firestore'); const fs = require('fs'); const firestore = new Firestore(); async function createBundle() { // Create a bundle with a unique ID const bundle = firestore.bundle('my-app-bundle'); // Add a named query const topProductsQuery = firestore .collection('products') .orderBy('sales', 'desc') .limit(50); const topProductsSnapshot = await topProductsQuery.get(); bundle.add('top-products', topProductsSnapshot); // Add individual documents const featuredDoc = await firestore.doc('featured/current').get(); bundle.add(featuredDoc); // Add another query const categoriesSnapshot = await firestore.collection('categories').get(); bundle.add('all-categories', categoriesSnapshot); // Build the bundle (returns a Buffer) const bundleBuffer = bundle.build(); // Save to file or serve via HTTP fs.writeFileSync('app-bundle.txt', bundleBuffer); // Or send as HTTP response // res.set('Content-Type', 'application/octet-stream'); // res.send(bundleBuffer); console.log(`Bundle created: ${bundleBuffer.length} bytes`); } ``` -------------------------------- ### Perform Collection Operations (Add and List Documents) Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Add documents with auto-generated IDs using add(), list documents with listDocuments(), and access subcollections. Also shows listing root and subcollections. ```javascript const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); async function collectionOperations() { const usersRef = firestore.collection('users'); // Add a document with auto-generated ID const newDocRef = await usersRef.add({ name: 'Bob', email: 'bob@example.com', createdAt: new Date() }); console.log('Added document with ID:', newDocRef.id); // Get a specific document in the collection const userDoc = usersRef.doc('specific-user-id'); // List all documents (including missing documents with subcollections) const documentRefs = await usersRef.listDocuments(); for (const docRef of documentRefs) { const doc = await docRef.get(); console.log(doc.id, doc.exists ? doc.data() : 'missing'); } // Access subcollection const postsRef = firestore.collection('users/user123/posts'); // List root collections const collections = await firestore.listCollections(); collections.forEach(col => console.log('Collection:', col.id)); // List subcollections of a document const docRef = firestore.doc('users/user123'); const subcollections = await docRef.listCollections(); subcollections.forEach(col => console.log('Subcollection:', col.id)); } ``` -------------------------------- ### Create a Document Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Creates a new document with the specified data at the given document reference. This operation is asynchronous and returns a Promise resolving to a WriteResult. ```typescript create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Promise; ``` -------------------------------- ### Lint and Fix Code Source: https://github.com/googleapis/nodejs-firestore/blob/main/CONTRIBUTING.md Run the linter and attempt to automatically fix any style issues. ```bash # Lint (and maybe fix) any changes: npm run fix ``` -------------------------------- ### Create Document Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Creates a new document with the provided data. This operation is atomic and will only succeed if the document does not already exist. ```APIDOC ## POST /documents/{collectionId}/{documentId} ### Description Creates a new document with the provided data. This operation is atomic and will only succeed if the document does not already exist. ### Method POST ### Endpoint /documents/{collectionId}/{documentId} ### Parameters #### Path Parameters - **collectionId** (string) - Required - The ID of the collection to create the document in. - **documentId** (string) - Required - The ID of the document to create. #### Request Body - **data** (object) - Required - The data to write to the document. ### Request Example ```json { "data": { "field1": "value1", "field2": 123 } } ``` ### Response #### Success Response (200) - **writeTime** (Timestamp) - The time at which the write was committed. #### Response Example ```json { "writeTime": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Perform Simple Queries with Filters, Sorting, and Pagination Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Demonstrates basic Firestore query operations including equality checks, array membership, range comparisons, ordering, and limiting results. ```javascript const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); async function simpleQueries() { const usersRef = firestore.collection('users'); // Simple equality query const activeUsers = await usersRef .where('status', '==', 'active') .get(); // Comparison operators: <, <=, ==, !=, >=, > const recentUsers = await usersRef .where('createdAt', '>', new Date('2024-01-01')) .get(); // Array contains const admins = await usersRef .where('roles', 'array-contains', 'admin') .get(); // Array contains any (OR for array membership) const staffOrAdmin = await usersRef .where('roles', 'array-contains-any', ['staff', 'admin']) .get(); // In query (field equals any value in list) const specificStatuses = await usersRef .where('status', 'in', ['active', 'pending']) .get(); // Not in query const notDeleted = await usersRef .where('status', 'not-in', ['deleted', 'banned']) .get(); // Order and limit const topUsers = await usersRef .orderBy('score', 'desc') .limit(10) .get(); // Get last N results (requires orderBy) const bottomUsers = await usersRef .orderBy('score', 'asc') .limitToLast(5) .get(); // Pagination with offset const page2 = await usersRef .orderBy('name') .offset(20) .limit(10) .get(); // Process results topUsers.forEach(doc => { console.log(doc.id, doc.data()); }); console.log('Total results:', topUsers.size); console.log('Empty?', topUsers.empty); } ``` -------------------------------- ### PlanSummary Class Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Represents a summary of a query plan. ```APIDOC ## PlanSummary Class ### Description Represents a summary of a query plan. ### Constructor (Undocumented) ``` -------------------------------- ### Utility Functions Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Utility functions for setting logging and handling timestamps. ```APIDOC ## setLogFunction ### Description Sets a custom function for logging messages. ### Method `setLogFunction(logger: ((msg: string) => void) | null): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Timestamp ### Description Represents a point in time. ### Method `constructor(seconds: number, nanoseconds: number)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### POST /transaction/create Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Creates a new document in the transaction. ```APIDOC ## POST /transaction/create ### Description Creates a new document within the current transaction context. ### Method POST ### Parameters #### Request Body - **documentRef** (firestore.DocumentReference) - Required - The reference to the document to create. - **data** (firestore.WithFieldValue) - Required - The data to write to the document. ``` -------------------------------- ### Expression Functions Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md A collection of beta functions for creating expressions, including comparisons, conditional logic, and data manipulation. ```APIDOC ## Expression Functions ### Comparison Functions - **greaterThan(left, right)**: Creates a greater-than expression. - **greaterThanOrEqual(left, right)**: Creates a greater-than-or-equal expression. ### Conditional Functions - **ifAbsent(ifExpr, elseExpr)**: Returns the else expression if the if expression is absent. - **ifError(tryExpr, catchExpr)**: Handles errors within expressions. ### Utility Functions - **isAbsent(value)**: Checks if a value is absent. - **isError(value)**: Checks if an expression resulted in an error. - **isType(fieldName, type)**: Checks if a field matches a specific type. - **join(array, delimiter)**: Joins an array field or expression with a delimiter. - **last(expression)**: Aggregate function to get the last value. - **length_2(expression)**: Function to get the length of a field or expression. ``` -------------------------------- ### ExplainResults Class Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Contains the results of an explained query, including both the metrics and the query snapshot. ```APIDOC ## ExplainResults ### Description Encapsulates the metrics and the resulting snapshot from an explained Firestore query. ### Properties - **metrics** (ExplainMetrics) - The metrics collected during query execution. - **snapshot** (T | null) - The query snapshot result. ``` -------------------------------- ### WriteBatch API Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Provides methods to create and manage batched write operations. ```APIDOC ## WriteBatch API ### Description Returns a `WriteBatch` object that can be used to perform atomic writes. ### Method batch() ### Endpoint N/A (Instance method) ### Response #### Success Response (200) - **WriteBatch** - An object representing a batch of writes. ``` -------------------------------- ### Configure Logging and Handle gRPC Errors Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Use setLogFunction to toggle SDK logging and switch statements to handle specific gRPC error codes during document operations. ```javascript const {Firestore, setLogFunction, GrpcStatus} = require('@google-cloud/firestore'); // Enable logging setLogFunction((msg) => { console.log(`[Firestore] ${msg}`); }); // Disable logging setLogFunction(null); const firestore = new Firestore(); async function errorHandling() { try { await firestore.doc('users/user123').get(); } catch (error) { // Check gRPC status codes switch (error.code) { case GrpcStatus.NOT_FOUND: console.log('Document not found'); break; case GrpcStatus.PERMISSION_DENIED: console.log('Access denied - check security rules'); break; case GrpcStatus.UNAVAILABLE: console.log('Service unavailable - retry later'); break; case GrpcStatus.DEADLINE_EXCEEDED: console.log('Request timed out'); break; case GrpcStatus.RESOURCE_EXHAUSTED: console.log('Quota exceeded - implement backoff'); break; default: console.log('Unknown error:', error.message); } } // Graceful shutdown process.on('SIGTERM', async () => { console.log('Shutting down...'); await firestore.terminate(); process.exit(0); }); } ``` -------------------------------- ### Perform high-throughput parallel writes with BulkWriter Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Use BulkWriter for efficient data migrations and bulk updates. It supports automatic batching, custom throttling, and granular error handling. ```javascript const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); async function bulkWriterExample() { // Create a BulkWriter with custom throttling const bulkWriter = firestore.bulkWriter({ throttling: { initialOpsPerSecond: 500, maxOpsPerSecond: 1000 } }); // Track successes and failures bulkWriter.onWriteResult((documentRef, result) => { console.log(`Wrote ${documentRef.path} at ${result.writeTime.toDate()}`); }); bulkWriter.onWriteError((error) => { if (error.failedAttempts < 3) { console.log(`Retrying ${error.documentRef.path}...`); return true; // Retry the operation } console.error(`Failed to write ${error.documentRef.path}:`, error.message); return false; // Don't retry }); // Queue write operations (don't await individual operations) for (let i = 0; i < 10000; i++) { const docRef = firestore.collection('items').doc(`item${i}`); bulkWriter.create(docRef, { index: i, value: Math.random() }).then(result => { // Optional: handle individual success }).catch(error => { // Optional: handle individual failure }); } // Flush pending writes (optional - useful for checkpoints) await bulkWriter.flush(); // Close and wait for all operations to complete await bulkWriter.close(); console.log('All writes completed'); } ``` -------------------------------- ### Set Document Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Sets data to a document. If the document does not exist, it will be created. If the document exists, its contents will be overwritten unless merge options are provided. ```APIDOC ## POST /documents/{collectionId}/{documentId} ### Description Sets data to a document. If the document does not exist, it will be created. If the document exists, its contents will be overwritten unless merge options are provided. ### Method POST ### Endpoint /documents/{collectionId}/{documentId} ### Parameters #### Path Parameters - **collectionId** (string) - Required - The ID of the collection containing the document. - **documentId** (string) - Required - The ID of the document to set. #### Request Body - **data** (object) - Required - The data to write to the document. - **options** (object) - Optional - Options for the set operation. - **merge** (boolean) - If true, only update the fields specified in the data, merging with existing fields. - **mergeFields** (array) - An array of field paths to merge. ### Request Example ```json { "data": { "field1": "value1", "field2": 123 }, "options": { "merge": true } } ``` ### Response #### Success Response (200) - **writeTime** (Timestamp) - The time at which the write was committed. #### Response Example ```json { "writeTime": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### PipelineSource Class Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Provides methods to create and manage Firestore pipelines. ```APIDOC ## PipelineSource Class ### Description Provides methods to create and manage Firestore pipelines. ### Constructor `constructor(db: Firestore)` ### Methods - **collection(collection: string | firestore.CollectionReference): Pipeline** Starts a pipeline from a collection reference. - **collection(options: firestore.Pipelines.CollectionStageOptions): Pipeline** Starts a pipeline from a collection reference with options. - **collectionGroup(collectionId: string): Pipeline** Starts a pipeline from a collection group. - **collectionGroup(options: firestore.Pipelines.CollectionGroupStageOptions): Pipeline** Starts a pipeline from a collection group with options. - **createFrom(query: firestore.VectorQuery): Pipeline** Creates a pipeline from a vector query. - **createFrom(query: firestore.Query): Pipeline** Creates a pipeline from a query. - **database(): Pipeline** Starts a pipeline from the database root. - **database(options: firestore.Pipelines.DatabaseStageOptions): Pipeline** Starts a pipeline from the database root with options. - **documents(docs: Array): Pipeline** Starts a pipeline from a list of document references. - **documents(options: firestore.Pipelines.DocumentsStageOptions): Pipeline** Starts a pipeline from a list of document references with options. - **_validateReference(reference: firestore.CollectionReference | firestore.DocumentReference): reference is CollectionReference | DocumentReference** Validates a reference to be a CollectionReference or DocumentReference. ``` -------------------------------- ### Query Methods Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Methods for constructing and executing Firestore queries. ```APIDOC ## select(...fieldPaths) ### Description Creates and returns a new Query that only returns the specified fields. ### Parameters #### Path Parameters - **fieldPaths** (Array) - Required - The fields to include in the result. ## startAfter(...fieldValuesOrDocumentSnapshot) ### Description Creates and returns a new Query that starts after the provided document or field values. ### Parameters #### Path Parameters - **fieldValuesOrDocumentSnapshot** (Array) - Required - The values or snapshot to start after. ## startAt(...fieldValuesOrDocumentSnapshot) ### Description Creates and returns a new Query that starts at the provided document or field values. ### Parameters #### Path Parameters - **fieldValuesOrDocumentSnapshot** (Array) - Required - The values or snapshot to start at. ## stream() ### Description Executes the query and returns a readable stream of the results. ### Response - **NodeJS.ReadableStream** - A stream of document results. ## where(fieldPath, opStr, value) ### Description Creates and returns a new Query with an additional filter. ### Parameters #### Path Parameters - **fieldPath** (string | FieldPath) - Required - The field to filter by. - **opStr** (firestore.WhereFilterOp) - Required - The comparison operator. - **value** (unknown) - Required - The value to compare against. ## withConverter(converter) ### Description Applies a custom data converter to the query. ### Parameters #### Path Parameters - **converter** (firestore.FirestoreDataConverter | null) - Required - The converter to apply. ``` -------------------------------- ### Ordering and Aggregation Functions Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Functions for defining order and performing average aggregations. ```APIDOC ## ascending ### Description Defines an ascending order for a field or expression. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "ascending(expr: Expression | fieldName: string)" } ``` ### Response #### Success Response (200) - **Ordering** (object) - An object representing the ascending order. #### Response Example ```json { "example": "Ordering" } ``` ## average ### Description Calculates the average of values. ### Method function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "average(expression: Expression | fieldName: string)" } ``` ### Response #### Success Response (200) - **AggregateFunction** (object) - An object representing the average aggregation. #### Response Example ```json { "example": "AggregateFunction" } ``` ``` -------------------------------- ### Listen to Document and Query Changes with onSnapshot Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Use `onSnapshot` to receive real-time updates for a single document or query results. Remember to unsubscribe from listeners when they are no longer needed to prevent memory leaks. ```javascript const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); function realtimeListeners() { // Listen to a single document const userRef = firestore.doc('users/user123'); const unsubscribeDoc = userRef.onSnapshot( (snapshot) => { if (snapshot.exists) { console.log('User data:', snapshot.data()); } else { console.log('User deleted'); } }, (error) => { console.error('Listener error:', error); } ); // Listen to a query const activeUsersQuery = firestore .collection('users') .where('status', '==', 'online'); const unsubscribeQuery = activeUsersQuery.onSnapshot( (snapshot) => { console.log(`${snapshot.size} users online`); // Track changes since last snapshot snapshot.docChanges().forEach(change => { if (change.type === 'added') { console.log('User came online:', change.doc.id); } if (change.type === 'modified') { console.log('User updated:', change.doc.id); } if (change.type === 'removed') { console.log('User went offline:', change.doc.id); } }); }, (error) => { console.error('Query listener error:', error); } ); // Unsubscribe when done (important to prevent memory leaks) // unsubscribeDoc(); // unsubscribeQuery(); } ``` -------------------------------- ### Explain Firestore Query Source: https://context7.com/googleapis/nodejs-firestore/llms.txt Analyzes Firestore query execution plans with or without statistics. Use 'analyze: true' for detailed execution metrics and result counts. ```javascript const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); async function queryExplain() { const query = firestore .collection('users') .where('status', '==', 'active') .where('age', '>=', 18) .orderBy('age') .limit(100); // Get query plan without executing const planOnly = await query.explain(); console.log('Query plan:', planOnly.planSummary); // Get plan with execution statistics const withStats = await query.explain({ analyze: true }); console.log('Plan:', withStats.planSummary); console.log('Execution stats:', withStats.executionStats); console.log('Results:', withStats.snapshot?.size); // Stream results with explain metrics const stream = query.explainStream({ analyze: true }); stream.on('data', (data) => { if (data.document) { console.log('Document:', data.document.id); } if (data.metrics) { console.log('Metrics:', data.metrics); } }); } ``` -------------------------------- ### ExplainMetrics Class Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Provides metrics regarding the execution of a Firestore query, including plan summaries and execution statistics. ```APIDOC ## ExplainMetrics ### Description Represents the metrics associated with a Firestore query execution plan. ### Properties - **executionStats** (ExecutionStats | null) - Statistics regarding the query execution duration and operations. - **planSummary** (PlanSummary) - A summary of the query execution plan. ``` -------------------------------- ### QueryPartition Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Represents a partition of a query, used for paginating query results. ```APIDOC ## QueryPartition ### Description Represents a partition of a Firestore query. This class is typically used internally for paginating query results, especially when dealing with large datasets. ### Properties - **endBefore** (unknown[] | undefined) - The cursor indicating the end of the partition (exclusive). - **startAt** (unknown[] | undefined) - The cursor indicating the start of the partition (inclusive). ### Methods - **toQuery()** (Query) - Converts this query partition back into a `Query` object. ### Example ```typescript // This class is usually managed internally by Firestore SDK for pagination. // Example of how it might be conceptually used: // const queryPartition = new QueryPartition(firestore, 'myCollection', converter, startAtCursor, endBeforeCursor); // const query = queryPartition.toQuery(); ``` ``` -------------------------------- ### POST /document/set Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Writes data to the document reference, either overwriting or merging with existing data. ```APIDOC ## POST /document/set ### Description Sets data on the document. If the document does not exist, it will be created. ### Method POST ### Parameters #### Request Body - **data** (Object) - Required - The data to write to the document. - **options** (Object) - Optional - Configuration options such as merge. ``` -------------------------------- ### VectorQueryOptions Interface Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Defines the options for configuring a vector query. ```APIDOC ## VectorQueryOptions Interface ### Description Options used to configure a vector search query. ### Fields - **distanceMeasure** (string) - Required - The distance measure to use ('EUCLIDEAN', 'COSINE', 'DOT_PRODUCT'). - **distanceResultField** (string | firestore.FieldPath) - Optional - The field to store the calculated distance in. - **distanceThreshold** (number) - Optional - The threshold for the distance measure. - **limit** (number) - Required - The maximum number of results to return. - **queryVector** (firestore.VectorValue | Array) - Required - The vector to query with. - **vectorField** (string | firestore.FieldPath) - Required - The field containing the vectors to search against. ``` -------------------------------- ### Pipeline Class Methods Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Methods for constructing and executing Firestore aggregation pipelines. ```APIDOC ## Pipeline Class ### Description The Pipeline class allows for the construction of complex data aggregation and transformation pipelines in Firestore. ### Methods - **addFields**(field: Selectable, ...additionalFields: Selectable[]): Pipeline - **aggregate**(accumulator: AliasedAggregate, ...additionalAccumulators: AliasedAggregate[]): Pipeline - **distinct**(group: string | Selectable, ...additionalGroups: Array): Pipeline - **execute**(pipelineExecuteOptions?: PipelineExecuteOptions): Promise - **findNearest**(options: FindNearestStageOptions): Pipeline - **limit**(limit: number): Pipeline - **offset**(offset: number): Pipeline - **removeFields**(fieldValue: Field | string, ...additionalFields: Array): Pipeline - **replaceWith**(expr: Expression | string): Pipeline - **sample**(documents: number): Pipeline - **select**(selection: Selectable | string, ...additionalSelections: Array): Pipeline ``` -------------------------------- ### PipelineSnapshot Class Source: https://github.com/googleapis/nodejs-firestore/blob/main/api-report/firestore.api.md Represents a snapshot of a pipeline's execution, including results and execution time. ```APIDOC ## PipelineSnapshot Class ### Description Represents a snapshot of a pipeline's execution, including results and execution time. ### Constructor `constructor(pipeline: Pipeline, results: PipelineResult[], executionTime?: Timestamp, explainStats?: ExplainStats)` ### Properties - **executionTime** (Timestamp) - The time the pipeline execution finished. - **explainStats** (ExplainStats | undefined) - Optional statistics from the explain plan. - **pipeline** (Pipeline) - The pipeline object. - **results** (PipelineResult[]) - An array of results from the pipeline execution. ```