Files
payload/packages/db-mongodb/src/create.ts
Alessio Gravili 5c16443431 fix: ensure updates to createdAt and updatedAt are respected (#13335)
Previously, when manually setting `createdAt` or `updatedAt` in a
`payload.db.*` or `payload.*` operation, the value may have been
ignored. In some cases it was _impossible_ to change the `updatedAt`
value, even when using direct db adapter calls. On top of that, this
behavior sometimes differed between db adapters. For example, mongodb
did accept `updatedAt` when calling `payload.db.updateVersion` -
postgres ignored it.

This PR changes this behavior to consistently respect `createdAt` and
`updatedAt` values for `payload.db.*` operations.

For `payload.*` operations, this also works with the following
exception:
- update operations do no respect `updatedAt`, as updates are commonly
performed by spreading the old data, e.g. `payload.update({ data:
{...oldData} })` - in these cases, we usually still want the `updatedAt`
to be updated. If you need to get around this, you can use the
`payload.db.updateOne` operation instead.

---
- To see the specific tasks where the Asana app for GitHub is being
used, see below:
  - https://app.asana.com/0/0/1210919646303994
2025-08-22 08:41:07 -04:00

70 lines
1.7 KiB
TypeScript

import type { Create } from 'payload'
import { type CreateOptions, Types } from 'mongoose'
import type { MongooseAdapter } from './index.js'
import { getCollection } from './utilities/getEntity.js'
import { getSession } from './utilities/getSession.js'
import { handleError } from './utilities/handleError.js'
import { transform } from './utilities/transform.js'
export const create: Create = async function create(
this: MongooseAdapter,
{ collection: collectionSlug, data, req, returning },
) {
const { collectionConfig, customIDType, Model } = getCollection({ adapter: this, collectionSlug })
const options: CreateOptions = {
session: await getSession(this, req),
// Timestamps are manually added by the write transform
timestamps: false,
}
let doc
if (!data.createdAt) {
data.createdAt = new Date().toISOString()
}
transform({
adapter: this,
data,
fields: collectionConfig.fields,
operation: 'write',
})
if (customIDType) {
data._id = data.id
} else if (this.allowIDOnCreate && data.id) {
try {
data._id = new Types.ObjectId(data.id as string)
} catch (error) {
this.payload.logger.error(
`It appears you passed ID to create operation data but it cannot be sanitized to ObjectID, value - ${JSON.stringify(data.id)}`,
)
throw error
}
}
try {
;[doc] = await Model.create([data], options)
} catch (error) {
handleError({ collection: collectionSlug, error, req })
}
if (returning === false) {
return null
}
doc = doc.toObject()
transform({
adapter: this,
data: doc,
fields: collectionConfig.fields,
operation: 'read',
})
return doc
}