Advertisement
nodejsdeveloperskh

aggregate - match - lookup - project - facet

Nov 28th, 2021
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface Query {
  2.     page?: number,
  3.     limit?: number,
  4.     otherFeild1?: string,
  5.     sort?: number,
  6.     sortBasedOn?: Array<'totalScore' | 'doneProjects' | 'workExperience' | 'commentNumber' | 'createdAt'>,
  7. }
  8. const queryParameters: Query = {
  9.     page,
  10.     limit,
  11.     otherFeild1,
  12.     sort,
  13.     sortBasedOn,
  14. };
  15. const $match = {
  16.     ...(otherFeild1 ? { otherFeild1 } : {})
  17. }
  18. const lookups = [
  19.     {
  20.         $lookup: {
  21.             from: 'collection-name1',
  22.             localField: 'collection-name1Id',
  23.             foreignField: '_id',
  24.             as: 'collection-name1',
  25.         },
  26.     },
  27.     {
  28.         $unwind: {
  29.             path: '$collection-name1',
  30.         },
  31.     },
  32. ];
  33. const $project = {
  34.     'field1.subField1': -1,
  35.     'field2': -1,
  36. };
  37. const $facet = {
  38.     documents: [
  39.         {
  40.             $sort: {
  41.                 ...(sortBasedOn.length > 0
  42.                     ? sortBasedOn.map((field) => ({ [field]: sort }))
  43.                     : { createdAt: -1 }),
  44.             },
  45.         },
  46.         { $skip: limit ?? * (page ?? 1 - 1) },
  47.         { $limit: limit ?? 10 },
  48.     ],
  49. };
  50.  
  51. const schemaDocuments: { documents: any[] }[] = await SchemaName.aggregate([
  52.     ...(Object.keys($match).length > 0 ? [{ $match }] : []),
  53.     ...lookups,
  54.     { $project },
  55.     { $facet },
  56. ]);
  57.  
  58. console.log(
  59.     schemaDocuments[0].documents
  60. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement