Skip to content

Commit 21606de

Browse files
authored
fix(db-mongodb): add validation to relationship ids (#8395)
fixes #8652
1 parent 7a0b419 commit 21606de

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

Diff for: packages/db-mongodb/src/utilities/sanitizeRelationshipIDs.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { CollectionConfig, Field, SanitizedConfig, TraverseFieldsCallback } from 'payload'
22

33
import mongoose from 'mongoose'
4-
import { traverseFields } from 'payload'
4+
import { APIError, traverseFields } from 'payload'
55
import { fieldAffectsData } from 'payload/shared'
66

77
type Args = {
@@ -31,7 +31,14 @@ const convertValue = ({
3131
)
3232

3333
if (!customIDField) {
34-
return new mongoose.Types.ObjectId(value)
34+
try {
35+
return new mongoose.Types.ObjectId(value)
36+
} catch (error) {
37+
throw new APIError(
38+
`Failed to create ObjectId from value: ${value}. Error: ${error.message}`,
39+
400,
40+
)
41+
}
3542
}
3643

3744
return value

Diff for: test/database/int.spec.ts

+21
Original file line numberDiff line numberDiff line change
@@ -741,4 +741,25 @@ describe('database', () => {
741741
}),
742742
).rejects.toThrow(QueryError)
743743
})
744+
745+
it('should not allow document creation with relationship data to an invalid document ID', async () => {
746+
let invalidDoc
747+
748+
try {
749+
invalidDoc = await payload.create({
750+
collection: 'relation-b',
751+
data: { title: 'invalid', relationship: 'not-real-id' },
752+
})
753+
} catch (error) {
754+
expect(error).toBeInstanceOf(Error)
755+
}
756+
757+
expect(invalidDoc).toBeUndefined()
758+
759+
const relationBDocs = await payload.find({
760+
collection: 'relation-b',
761+
})
762+
763+
expect(relationBDocs.docs).toHaveLength(0)
764+
})
744765
})

0 commit comments

Comments
 (0)