Skip to content

fix(injectModel): include missing-field documents in required-field duplicate precheck before unique index creation #67

@coderabbitai

Description

@coderabbitai

Summary

In packages/common/src/utils/injectModel.js, the getUniqueFieldFilter function currently filters required fields with { $exists: true }. This excludes legacy documents where the field is missing entirely.

A full unique index still treats repeated missing values as duplicate nulls, so the precheck can pass and createIndex() may then fail at the DB level — bypassing the intended duplicate-detection guard.

Proposed Fix

 function getUniqueFieldFilter(fieldKey, isRequired) {
   if (isRequired) {
-    return { [fieldKey]: { $exists: true } };
+    return {};
   }

   return { [fieldKey]: { $exists: true, $ne: null } };
 }

By returning an empty filter {} for required fields, findDuplicates() will scan all documents (including those missing the field), so duplicate missing/null values are detected before createIndex() runs.

References

Requested by @yash-pouranik

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions