• Queries the specified collection in Firestore based on the provided conditions and returns an array of documents that match the conditions.

    Throws

    Throws an exception with an error message if an error occurs.

    Example

    import { firestore } from 'firebase-admin'
    import { query } from '@skeet-framework/firestore'
    const db = firestore();

    // Simple query to get users over 25 years old
    const simpleConditions: QueryCondition[] = [
    { field: "age", operator: ">", value: 25 }
    ];

    // Advanced query to get users over 25 years old, ordered by desc
    // Limitations: If you include a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field
    // So we can't use multiple fields with a range comparison for now.
    // https://firebase.google.com/docs/firestore/query-data/order-limit-data
    const advancedConditions: QueryCondition[] = [
    { field: 'age', operator: '>', value: 25 },
    { field: 'age', orderDirection: 'desc' },
    ]

    // Query to get users over 25 years old and limit the results to 5
    const limitedConditions: QueryCondition[] = [
    { field: "age", operator: ">", value: 25 },
    { limit: 5 }
    ];

    async function run() {
    try {
    const path = 'Users';

    // Using the simple conditions
    const usersByAge = await query<User>(db, path, simpleConditions);
    console.log(`Found ${usersByAge.length} users over 25 years old.`);

    // Using the advanced conditions
    const orderedUsers = await query<User>(db, path, advancedConditions);
    console.log(`Found ${orderedUsers.length} users over 25 years old, ordered by name.`);

    // Using the limited conditions
    const limitedUsers = await query<User>(db, path, limitedConditions);
    console.log(`Found ${limitedUsers.length} users over 25 years old, limited to 5.`);

    } catch (error) {
    console.error(`Error querying collection: ${error}`);
    }
    }

    run();

    Type Parameters

    • T extends DocumentData

    Parameters

    • db: Firestore

      The instance of the Firestore database to use.

    • collectionPath: string

      The path of the collection to be queried.

    • conditions: QueryCondition[]

      An array of conditions to apply to the query.

    Returns Promise<T[]>

    An array of documents from the collection that match the conditions.

Generated using TypeDoc