feat(db-*): allow to thread id to create operation data without custom IDs (#11709)

Fixes https://github.com/payloadcms/payload/issues/6884

Adds a new flag `acceptIDOnCreate` that allows you to thread your own
`id` to `payload.create` `data`, for example:

```ts
// doc created with id 1
const doc = await payload.create({ collection: 'posts', data: {id: 1, title: "my title"}})
```

```ts
import { Types } from 'mongoose'
const id = new Types.ObjectId().toHexString()
const doc = await payload.create({ collection: 'posts', data: {id, title: "my title"}})
```
This commit is contained in:
Sasha
2025-03-18 05:48:35 +02:00
committed by GitHub
parent 95821c6136
commit f442d22237
17 changed files with 173 additions and 18 deletions

View File

@@ -12,7 +12,7 @@ import { type Table } from 'drizzle-orm'
import * as drizzlePg from 'drizzle-orm/pg-core'
import * as drizzleSqlite from 'drizzle-orm/sqlite-core'
import fs from 'fs'
import { Types } from 'mongoose'
import mongoose, { Types } from 'mongoose'
import path from 'path'
import {
commitTransaction,
@@ -306,6 +306,81 @@ describe('database', () => {
})
})
describe('allow ID on create', () => {
beforeAll(() => {
payload.db.allowIDOnCreate = true
payload.config.db.allowIDOnCreate = true
})
afterAll(() => {
payload.db.allowIDOnCreate = false
payload.config.db.allowIDOnCreate = false
})
it('Local API - accepts ID on create', async () => {
let id: any = null
if (payload.db.name === 'mongoose') {
id = new mongoose.Types.ObjectId().toHexString()
} else if (payload.db.idType === 'uuid') {
id = randomUUID()
} else {
id = 9999
}
const post = await payload.create({ collection: 'posts', data: { id, title: 'created' } })
expect(post.id).toBe(id)
})
it('REST API - accepts ID on create', async () => {
let id: any = null
if (payload.db.name === 'mongoose') {
id = new mongoose.Types.ObjectId().toHexString()
} else if (payload.db.idType === 'uuid') {
id = randomUUID()
} else {
id = 99999
}
const response = await restClient.POST(`/posts`, {
body: JSON.stringify({
id,
title: 'created',
}),
})
const post = await response.json()
expect(post.doc.id).toBe(id)
})
it('GraphQL - accepts ID on create', async () => {
let id: any = null
if (payload.db.name === 'mongoose') {
id = new mongoose.Types.ObjectId().toHexString()
} else if (payload.db.idType === 'uuid') {
id = randomUUID()
} else {
id = 999999
}
const query = `mutation {
createPost(data: {title: "created", id: ${typeof id === 'string' ? `"${id}"` : id}}) {
id
title
}
}`
const res = await restClient
.GRAPHQL_POST({ body: JSON.stringify({ query }) })
.then((res) => res.json())
const doc = res.data.createPost
expect(doc).toMatchObject({ title: 'created', id })
expect(doc.id).toBe(id)
})
})
describe('Compound Indexes', () => {
beforeEach(async () => {
await payload.delete({ collection: 'compound-indexes', where: {} })