fix(db-mongodb): add validation to relationship ids (#8395)
fixes https://github.com/payloadcms/payload/issues/8652
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import type { CollectionConfig, Field, SanitizedConfig, TraverseFieldsCallback } from 'payload'
|
||||
|
||||
import mongoose from 'mongoose'
|
||||
import { traverseFields } from 'payload'
|
||||
import { APIError, traverseFields } from 'payload'
|
||||
import { fieldAffectsData } from 'payload/shared'
|
||||
|
||||
type Args = {
|
||||
@@ -31,7 +31,14 @@ const convertValue = ({
|
||||
)
|
||||
|
||||
if (!customIDField) {
|
||||
return new mongoose.Types.ObjectId(value)
|
||||
try {
|
||||
return new mongoose.Types.ObjectId(value)
|
||||
} catch (error) {
|
||||
throw new APIError(
|
||||
`Failed to create ObjectId from value: ${value}. Error: ${error.message}`,
|
||||
400,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
|
||||
@@ -741,4 +741,25 @@ describe('database', () => {
|
||||
}),
|
||||
).rejects.toThrow(QueryError)
|
||||
})
|
||||
|
||||
it('should not allow document creation with relationship data to an invalid document ID', async () => {
|
||||
let invalidDoc
|
||||
|
||||
try {
|
||||
invalidDoc = await payload.create({
|
||||
collection: 'relation-b',
|
||||
data: { title: 'invalid', relationship: 'not-real-id' },
|
||||
})
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
}
|
||||
|
||||
expect(invalidDoc).toBeUndefined()
|
||||
|
||||
const relationBDocs = await payload.find({
|
||||
collection: 'relation-b',
|
||||
})
|
||||
|
||||
expect(relationBDocs.docs).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user