lucasrochagit / nest-mongo-query-parser

A MongoDB query string parser to be used in applications developed with NestJS.
Apache License 2.0
12 stars 8 forks source link

how to filter by objectId ? #18

Closed j-vitali closed 5 months ago

j-vitali commented 5 months ago

Hi all, anyone jnows how to filter by objectId ? Basically I have a findAll() function that must read profileId (inside mongo it's a objectId) from params.

My actual query:

  @Get()
  async findAll(@MongoQuery() query: MongoQueryModel): Promise<{
    data: ExperienceRTO[];
    pagination: {
      page: number;
      pageCount: number;
      pageSize: number;
      total: number;
    };
  }> {
    const { data, pageSize, total } = await this.profileExperiencesService.findAll(query);

    // Calculate pagination values
    const page = Math.floor(query.skip / query.limit) + 1;
    const pageCount = Math.ceil(total / query.limit ?? 100);
    // Return data array and pagination schema
    return {
      data,
      pagination: {
        page: page || 1,
        pageSize,
        pageCount,
        total,
      },
    };
  }
lucasrochagit commented 5 months ago

Hello @j-vitali,

Currently, the library does not identify whether a filter is an objectId string and transforms it into an ObjectId, so if you need to make this query, you will need to treat the value before passing params to service. You can do the following:

GET /resources?profileId=6606f647c747219eee8d18a4

And in the code:

  ...
  import { isValidObjectId, Types } from 'mongoose';
  ...

    @Get()
  async findAll(@MongoQuery() query: MongoQueryModel): Promise<{
    data: ExperienceRTO[];
    pagination: {
      page: number;
      pageCount: number;
      pageSize: number;
      total: number;
    };
  }> {
    const profileId = query.filter.profileId;
    if (profileId && isValidObjectId(profileId)) {
      // this method overrides the field profileId in query filters
      query.addFilter({ profileId: new mongoose.Types.ObjectId(profileId) }); 
    }
    const { data, pageSize, total } =
      await this.profileExperiencesService.findAll(query);

    // Calculate pagination values
    const page = Math.floor(query.skip / query.limit) + 1;
    const pageCount = Math.ceil(total / query.limit ?? 100);
    // Return data array and pagination schema
    return {
      data,
      pagination: {
        page: page || 1,
        pageSize,
        pageCount,
        total,
      },
    };
  }

And you can do the search with profileId as ObjectId.