Skip to content

Commit 2acf9b1

Browse files
committed
fix: ensure nested autoValue is called for modifiers that don't set the parent
fixes #277
1 parent ded2a35 commit 2acf9b1

3 files changed

+51
-0
lines changed

src/clean/getPositionsForAutoValue.ts

+14
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { getLastPartOfKey, getParentOfKey } from '../utility/index.js'
55
interface GetPositionsForAutoValueProps {
66
fieldName: string
77
isModifier?: boolean
8+
isUpsert?: boolean
89
mongoObject: MongoObject
910
}
1011

@@ -42,6 +43,7 @@ interface PositionInfo {
4243
export default function getPositionsForAutoValue ({
4344
fieldName,
4445
isModifier,
46+
isUpsert,
4547
mongoObject
4648
}: GetPositionsForAutoValueProps): PositionInfo[] {
4749
// Positions for this field
@@ -130,5 +132,17 @@ export default function getPositionsForAutoValue ({
130132
})
131133
}
132134

135+
// If we made it this far, we still want to call the autoValue
136+
// function once for the field, so we'll add a would-be position for it.
137+
if (positions.length === 0 && isModifier === true && isUpsert !== true) {
138+
positions.push({
139+
key: fieldName,
140+
// @ts-expect-error incorrect type in mongo-object package
141+
value: undefined,
142+
operator: '$set',
143+
position: `$set[${fieldName}]`
144+
})
145+
}
146+
133147
return positions
134148
}

src/clean/setAutoValues.ts

+1
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ function setAutoValues (
6969
const positions = getPositionsForAutoValue({
7070
fieldName,
7171
isModifier,
72+
isUpsert,
7273
mongoObject
7374
})
7475

test/SimpleSchema_autoValueFunctions.tests.ts

+36
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,40 @@ describe('SimpleSchema - autoValueFunctions', function () {
153153
expect(autoValueFunctions[1].fieldName).toBe('a.b.$.z')
154154
expect(autoValueFunctions[1].closestSubschemaFieldName).toBe('a.b.$')
155155
})
156+
157+
it('modifier with autovalue in subschema', function () {
158+
const datesSchema = new SimpleSchema({
159+
updatedAt: {
160+
type: Date,
161+
label: 'Updated At',
162+
optional: true,
163+
autoValue: function () {
164+
return new Date()
165+
}
166+
}
167+
})
168+
169+
const schema = new SimpleSchema({
170+
otherStuff: {
171+
type: String,
172+
optional: true
173+
},
174+
dates: {
175+
type: datesSchema,
176+
label: 'Dates',
177+
optional: true,
178+
defaultValue: {}
179+
}
180+
})
181+
182+
const modifier = {
183+
$set: { otherStuff: 'someOtherString' }
184+
}
185+
186+
const cleanedModifier = schema.clean(modifier, {
187+
isModifier: true
188+
}) as any
189+
expect(cleanedModifier.$set['dates.updatedAt']).not.toBeUndefined()
190+
expect(cleanedModifier.$set['dates.updatedAt']).toBeInstanceOf(Date)
191+
})
156192
})

0 commit comments

Comments
 (0)