Files
payload/packages/db-mongodb/src/createVersion.ts
James Mikrut f96cf593ce feat: add jsonParse flag to mongooseAdapter that preserves existing, untracked MongoDB data types (#7338)
## Description

Preserves external data structures stored in MongoDB by avoiding the use
of `JSON.parse(JSON.stringify(mongooseDoc))`.

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository.

## Type of change

- [x] New feature (non-breaking change which adds functionality)

## Checklist:

- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] Existing test suite passes locally with my changes
2024-07-24 14:02:06 -04:00

73 lines
1.4 KiB
TypeScript

import type { CreateVersion } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from '.'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const createVersion: CreateVersion = async function createVersion(
this: MongooseAdapter,
{
autosave,
collectionSlug,
createdAt,
parent,
req = {} as PayloadRequest,
updatedAt,
versionData,
},
) {
const VersionModel = this.versions[collectionSlug]
const options = await withSession(this, req)
const [doc] = await VersionModel.create(
[
{
autosave,
createdAt,
latest: true,
parent,
updatedAt,
version: versionData,
},
],
options,
req,
)
await VersionModel.updateMany(
{
$and: [
{
_id: {
$ne: doc._id,
},
},
{
parent: {
$eq: parent,
},
},
{
latest: {
$eq: true,
},
},
],
},
{ $unset: { latest: 1 } },
options,
)
const result = this.jsonParse ? JSON.parse(JSON.stringify(doc)) : doc.toObject()
const verificationToken = doc._verificationToken
if (verificationToken) {
result._verificationToken = verificationToken
}
return sanitizeInternalFields(result)
}