Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

mongoose pagination

  async getAllUsers(query: DTOUsersPagination): Promise<APIResponse> {
    try {
      if (!query.hasOwnProperty('limit') && !query.hasOwnProperty('offset') && !query.hasOwnProperty('sort')) {
        query.limit = 10
        query.offset = 0
        query.sort = 'asc' ? 1 : -1
      }

      let getAllUsers: IUsers[] = []

      if (query.hasOwnProperty('filter') && JSON.parse(query.filter as any) == true) {
        const schemaFields: string[] = Object.keys(this.users.model.schema['paths'])
        const groupQuery: string[] = Object.keys(query)

        const getKey: any = schemaFields.find((val: string) => groupQuery.indexOf(val) !== -1 && val)
        const getValue: any = schemaFields.find((val: string) => query[val] && val)

        if (!getKey && !getValue) throw apiResponse(status.BAD_REQUEST, 'filter schema field not valid')

        getAllUsers = await this.users.model
          .find({}, { __v: 0 })
          .where({ [getKey]: query[getValue] })
          .limit(query.limit)
          .skip(query.offset)
          .sort({ _id: query.sort })
      } else {
        getAllUsers = await this.users.model.find({}, { __v: 0 }).limit(query.limit).skip(query.offset).sort({ _id: query.sort })
      }

      const currentPage: number = 1
      const countData: number = await this.users.model.count()
      const totalPage: number = Math.ceil(countData / query.page)

      const pagination: Record<string, any> = {
        count: countData,
        limit: +query.limit,
        offset: +query.offset,
        currentPage: +query.offset > 0 ? currentPage + 1 : currentPage,
        perPage: +query.page,
        totalPage: totalPage
      }

      return Promise.resolve(apiResponse(status.OK, 'Users already to use', getAllUsers, pagination))
    } catch (e: any) {
      return Promise.reject(apiResponse(e.stat_code || status.BAD_REQUEST, e.stat_message || e.message))
    }
  }
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #mongoose #pagination
ADD COMMENT
Topic
Name
9+3 =