diff --git a/packages/db-mongodb/src/utilities/sanitizeRelationshipIDs.ts b/packages/db-mongodb/src/utilities/sanitizeRelationshipIDs.ts index 7b33c56bfc..bb15fc769c 100644 --- a/packages/db-mongodb/src/utilities/sanitizeRelationshipIDs.ts +++ b/packages/db-mongodb/src/utilities/sanitizeRelationshipIDs.ts @@ -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 diff --git a/test/database/int.spec.ts b/test/database/int.spec.ts index 069c277379..5c27156156 100644 --- a/test/database/int.spec.ts +++ b/test/database/int.spec.ts @@ -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) + }) })