From a5bbc5e73d562465b180e24940379c63b0f079f4 Mon Sep 17 00:00:00 2001 From: Sander Hoogendoorn Date: Wed, 31 Jul 2024 21:17:32 +0200 Subject: [PATCH] fix: added multiply to Stages.ts --- packages/easy-mongo/src/Stages.ts | 3 ++- packages/easy-mongo/test/Stages.test.ts | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/easy-mongo/src/Stages.ts b/packages/easy-mongo/src/Stages.ts index 0e07e62be..b091998b7 100644 --- a/packages/easy-mongo/src/Stages.ts +++ b/packages/easy-mongo/src/Stages.ts @@ -24,7 +24,7 @@ import { toMongoType } from './Utils'; export const asc = 1; export const desc = -1; -export type Accumulators = '$sum' | '$count' | '$avg' | '$first' | '$last' | '$min' | '$max' | '$push' | '$addToSet'; +export type Accumulators = '$sum' | '$count' | '$multiply' | '$avg' | '$first' | '$last' | '$min' | '$max' | '$push' | '$addToSet'; export type Accumulator = PartialRecord; export class FilterBuilder { @@ -116,6 +116,7 @@ export const stages = { count: (): Accumulator => ({ $count: {} }), sum: (from?: string): Accumulator => (isDefined(from) ? { $sum: `$${from}` } : { $sum: 1 }), avg: (from?: string) => ({ $avg: `$${from}` }), + multiply: (...multiply: string[]) => ({ $multiply: multiply.map(m => `$${m}`) }), first: (from?: string): Accumulator => ({ $first: `$${from}` }), last: (from?: string): Accumulator => ({ $last: `$${from}` }), min: (from?: string): Accumulator => ({ $min: `$${from}` }), diff --git a/packages/easy-mongo/test/Stages.test.ts b/packages/easy-mongo/test/Stages.test.ts index e9f08aef7..9df2b68e0 100644 --- a/packages/easy-mongo/test/Stages.test.ts +++ b/packages/easy-mongo/test/Stages.test.ts @@ -185,7 +185,7 @@ describe('Stages', () => { }); // Group - const { group, addToSet, count, avg, sum, first, last, min, max, date, push } = stages.group; + const { group, addToSet, multiply, count, avg, sum, first, last, min, max, date, push } = stages.group; test('filter undefined', () => { expect(decode.fields({ total: count(), remove: undefined })).toStrictEqual({ total: { $count: {} } }); @@ -269,6 +269,16 @@ describe('Stages', () => { expect(g).toStrictEqual({ $group: { _id: '$brandId', total: { $addToSet: '$count' } } }); }); + test('groupBy string id and multiply', () => { + const g = group({ total: multiply('count', 'unitPrice') }).by('brandId'); + expect(g).toStrictEqual({ $group: { _id: '$brandId', total: { $multiply: ['$count', '$unitPrice'] } } }); + }); + + test('groupBy string id and multiply in $sum', () => { + const g = group({ total: { $sum: multiply('count', 'unitPrice') } }).by('brandId'); + expect(g).toStrictEqual({ $group: { _id: '$brandId', total: { $sum: { $multiply: ['$count', '$unitPrice'] } } } }); + }); + test('groupBy filter id and single field', () => { const g = group({ count: count() }).by({ 'created.when': date() }); expect(g).toStrictEqual({