Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/mongodb/src/converters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const keywordObjectId = {
parentData[parentDataProperty] = new ObjectId(value)
return true
} catch (error) {
throw new Error(`invalid objectid for property "${parentDataProperty}"`)
return false
}
}
}
Expand Down
26 changes: 24 additions & 2 deletions packages/mongodb/test/converters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ describe('objectid keyword', () => {
assert.equal(typeof data.otherId, 'string')
})

it('fails on invalid objectids', async () => {
it('fails validation on invalid objectids', async () => {
const schema = {
type: 'object',
properties: {
Expand All @@ -104,6 +104,28 @@ describe('objectid keyword', () => {
}
assert.equal(typeof data._id, 'string')

assert.throws(() => validate(data), /invalid objectid for property "_id"/)
assert.equal(validate(data), false)
assert.equal(validate.errors?.[0].keyword, 'objectid')
})

it('continues validating nullable unions when an objectid branch fails', async () => {
const nullableValidator = new Ajv({ coerceTypes: true, useDefaults: true })
nullableValidator.addKeyword(keywordObjectId)

const schema: any = {
type: 'object',
properties: {
refId: {
anyOf: [{ type: 'string', objectid: true }, { type: 'null' }],
default: null
}
},
additionalProperties: false
}
const validate = nullableValidator.compile(schema)
const data: { refId?: ObjectId | null } = {}

assert.equal(validate(data), true)
assert.equal(data.refId, null)
})
})