Skip to content

Commit d97a822

Browse files
authored
test: speed up mongo test resets by preserving indexes (#14861)
MongoDB test resets (clearAndSeedEverything) were taking 4-5s because we were dropping the entire database and recreating indexes every time. Now we just delete documents (like Postgres does), which preserves indexes and makes consecutive test runs much faster.
1 parent 8c5c1fb commit d97a822

2 files changed

Lines changed: 11 additions & 29 deletions

File tree

test/helpers/reset.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,17 @@ export async function resetDB(_payload: Payload, collectionSlugs: string[]) {
1010
if (!firstCollectionSlug?.length) {
1111
throw new Error('No collection slugs provided to reset the database.')
1212
}
13-
await _payload.db.collections[firstCollectionSlug]?.db.dropDatabase()
13+
14+
// Delete all documents from each collection instead of dropping the database.
15+
// This preserves indexes and is much faster for consecutive test runs.
16+
const mongooseCollections = _payload.db.collections[firstCollectionSlug]?.db.collections
17+
if (mongooseCollections) {
18+
await Promise.all(
19+
Object.values(mongooseCollections).map(async (collection: any) => {
20+
await collection.deleteMany({})
21+
}),
22+
)
23+
}
1424
} else if ('drizzle' in _payload.db) {
1525
const db = _payload.db as unknown as DrizzleAdapter
1626

test/helpers/seed.ts

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import path from 'path'
44
import { type Payload } from 'payload'
55

66
import { isErrorWithCode } from './isErrorWithCode.js'
7-
import { isMongoose } from './isMongoose.js'
87
import { resetDB } from './reset.js'
98
import { createSnapshot, dbSnapshot, restoreFromSnapshot, uploadsDirCache } from './snapshot.js'
109

@@ -120,33 +119,6 @@ export async function seedDB({
120119
restored = true
121120
}
122121

123-
/**
124-
* Mongoose: Re-create indexes
125-
* Postgres: No need for any action here, since we only delete the table data and no schemas
126-
*/
127-
// Dropping the db breaks indexes (on mongoose - did not test extensively on postgres yet), so we recreate them here
128-
try {
129-
if (isMongoose(_payload)) {
130-
await Promise.all([
131-
...collectionSlugs
132-
.filter(
133-
(collectionSlug) =>
134-
['payload-migrations', 'payload-preferences', 'payload-locked-documents'].indexOf(
135-
collectionSlug,
136-
) === -1,
137-
)
138-
.map(async (collectionSlug) => {
139-
await _payload.db.collections[collectionSlug]?.createIndexes({
140-
// Blocks writes (doesn't matter here) but faster
141-
background: false,
142-
})
143-
}),
144-
])
145-
}
146-
} catch (e) {
147-
console.error('Error in operation (re-creating indexes):', e)
148-
}
149-
150122
/**
151123
* If a snapshot was restored, we don't need to seed the database
152124
*/

0 commit comments

Comments
 (0)