Skip to content

Commit 4ce3cc5

Browse files
committed
fix(api): make database seeding idempotent and preserve IDs
Corrects the `DatabaseSeedingService` to ensure the seeding process is idempotent and correctly preserves the relationships between fixture documents. The previous implementation had two critical bugs: 1. It generated a new, random `ObjectId` on every run, which broke all predefined relationships between entities. 2. It used an empty filter `{}` in its `replaceOne` operation, causing it to overwrite existing documents incorrectly on subsequent runs. This fix addresses these issues by: - Using the predefined hex string ID from each fixture item to create a deterministic `ObjectId`. - Using `updateOne` with a specific `_id` in the filter, ensuring that the correct document is targeted. - Using the `$set` operator with `upsert: true` to safely insert or update the document, making the entire process idempotent.
1 parent 6e84bcf commit 4ce3cc5

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

lib/src/services/database_seeding_service.dart

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,19 @@ class DatabaseSeedingService {
8080
final operations = <Map<String, Object>>[];
8181

8282
for (final item in fixtureData) {
83-
// Generate a new ObjectId for each document
84-
final objectId = ObjectId();
83+
// Use the predefined hex string ID from the fixture to create a
84+
// deterministic ObjectId. This is crucial for maintaining relationships
85+
// between documents (e.g., a headline and its source).
86+
final objectId = ObjectId.fromHexString(getId(item));
8587
final document = toJson(item)..remove('id');
8688

8789
operations.add({
88-
'replaceOne': {
89-
'filter': {}, // Match all documents (replace existing or insert new)
90-
'replacement': document,
90+
// Use updateOne with $set to be less destructive than replaceOne.
91+
'updateOne': {
92+
// Filter by the specific, deterministic _id.
93+
'filter': {'_id': objectId},
94+
// Set the fields of the document.
95+
'update': {'\$set': document},
9196
'upsert': true,
9297
},
9398
});

0 commit comments

Comments
 (0)