firestore query to get "next lesson" from list of lessons in a program

Discussão em 'Angular' iniciado por J King, Dezembro 16, 2024.

  1. J King

    J King Guest

    I have a firestore db that has a list of "programs" that a user can sign up for. Each program has a list of sessions/lessons that can be completed. The user can have more than one program set as "active", meaning they are working on it.

    I am trying to build a query that will get the "next" lesson for each active program the user has enrolled in.

    Each session/lesson has a separate detail and preview document as a sub collection of the program document. so I am looking to get a list of the "next session" previews based on ordering by week and day number. I also have a top level collection called userProgramProgress that has the following fields:

    export interface UserProgramProgress {
    docId: string,
    userId: string,
    programId: string,
    isActive: boolean,
    isComplete: boolean,
    startDate: Date,
    endDate: Date,
    completedSessions: string[],
    };


    completedSessions is an array of the documentId's of the sessions that have been completed.

    So I get the UserProgramProgress documents like this:


    private userProgramProgressCollection = collection(
    this.firestore,
    'userProgramProgress'
    );

    const activeProgramsQuery = query(
    this.userProgramProgressCollection,
    where('userId', '==', uid),
    where('isActive', '==', true)
    );


    Then I need to get the next session for each program and combine them into one list to return to the user.

    something like this:

    const cd = collectionData(activeProgramsQuery, {
    idField: 'docId',
    }).pipe(
    switchMap((programs) =>
    programs.map((p) => p as UserProgramProgress)
    ),
    switchMap((program) => {
    // use program completted sessions to get next sessions
    const sessionCount = program.completedSessions.length ?? 0;

    const programPreviewCollection = collection(
    this.firestore,
    '/trainingPrograms/' + program.programId + '/programSessionPreview'
    );

    const recordsQuery = query(
    programPreviewCollection,
    where('programId', '==', program.programId),
    orderBy('programWeek', 'asc'),
    orderBy('programDay', 'asc'),
    limit(sessionCount + 1)
    );

    return collectionData(recordsQuery, {
    idField: 'docId',
    });
    })
    );


    I am new to no-sql databse and need to know if I am on the right track. I plan to use the results here to loop through and get the records but this will result in a lot of reads.

    for context this is inside an angular 18 app

    QUESTION:


    IS this the right direction for handling this scenario or should I do it a different way?

    Continue reading...

Compartilhe esta Página