diff --git a/src/clean/getPositionsForAutoValue.ts b/src/clean/getPositionsForAutoValue.ts index 31aaefb..b98b01d 100644 --- a/src/clean/getPositionsForAutoValue.ts +++ b/src/clean/getPositionsForAutoValue.ts @@ -5,6 +5,7 @@ import { getLastPartOfKey, getParentOfKey } from '../utility/index.js' interface GetPositionsForAutoValueProps { fieldName: string isModifier?: boolean + isUpsert?: boolean mongoObject: MongoObject } @@ -42,6 +43,7 @@ interface PositionInfo { export default function getPositionsForAutoValue ({ fieldName, isModifier, + isUpsert, mongoObject }: GetPositionsForAutoValueProps): PositionInfo[] { // Positions for this field @@ -130,5 +132,17 @@ export default function getPositionsForAutoValue ({ }) } + // If we made it this far, we still want to call the autoValue + // function once for the field, so we'll add a would-be position for it. + if (positions.length === 0 && isModifier === true && isUpsert !== true) { + positions.push({ + key: fieldName, + // @ts-expect-error incorrect type in mongo-object package + value: undefined, + operator: '$set', + position: `$set[${fieldName}]` + }) + } + return positions } diff --git a/src/clean/setAutoValues.ts b/src/clean/setAutoValues.ts index 8b1c33a..c01efa9 100755 --- a/src/clean/setAutoValues.ts +++ b/src/clean/setAutoValues.ts @@ -69,6 +69,7 @@ function setAutoValues ( const positions = getPositionsForAutoValue({ fieldName, isModifier, + isUpsert, mongoObject }) diff --git a/test/SimpleSchema_autoValueFunctions.tests.ts b/test/SimpleSchema_autoValueFunctions.tests.ts index 9729022..1dca55d 100644 --- a/test/SimpleSchema_autoValueFunctions.tests.ts +++ b/test/SimpleSchema_autoValueFunctions.tests.ts @@ -153,4 +153,40 @@ describe('SimpleSchema - autoValueFunctions', function () { expect(autoValueFunctions[1].fieldName).toBe('a.b.$.z') expect(autoValueFunctions[1].closestSubschemaFieldName).toBe('a.b.$') }) + + it('modifier with autovalue in subschema', function () { + const datesSchema = new SimpleSchema({ + updatedAt: { + type: Date, + label: 'Updated At', + optional: true, + autoValue: function () { + return new Date() + } + } + }) + + const schema = new SimpleSchema({ + otherStuff: { + type: String, + optional: true + }, + dates: { + type: datesSchema, + label: 'Dates', + optional: true, + defaultValue: {} + } + }) + + const modifier = { + $set: { otherStuff: 'someOtherString' } + } + + const cleanedModifier = schema.clean(modifier, { + isModifier: true + }) as any + expect(cleanedModifier.$set['dates.updatedAt']).not.toBeUndefined() + expect(cleanedModifier.$set['dates.updatedAt']).toBeInstanceOf(Date) + }) })