fix(server): drop stale indexes before renaming the tenant key

Two defects found by running migration 0004 against a seeded legacy database.

A unique index on org_id treats a missing org_id as null. Renaming the field
strips it, so the second document collided and the whole update failed:

  E11000 duplicate key error collection: instance_oidc index: org_id_1
  dup key: { org_id: null }

The index cleanup therefore has to run BEFORE the field rename, not after.
rename-rollback needs the symmetric step for instance_id, or reverting hits
the same wall.

The detection also silently matched nothing: the driver decodes an index key
document as bson.D, not bson.M, so the type assertion always failed and no
index was ever dropped. IndexKeyedOn now handles both.
This commit is contained in:
2026-07-24 14:15:05 +01:00
parent 50a06dfdc0
commit 539403cccf
2 changed files with 78 additions and 30 deletions
+9
View File
@@ -41,6 +41,15 @@ func main() {
db := client.Database(*dbName)
// Drop indexes keyed on instance_id first, for the same reason the forward
// migration drops the org_id ones: a unique index treats the missing field
// as null and rejects the second document the rename touches.
for _, c := range services.ScopedCollections {
if err := services.DropIndexesKeyedOn(ctx, db, c, "instance_id"); err != nil {
log.Fatalf("%v", err)
}
}
for _, c := range services.ScopedCollections {
res, err := db.Collection(c).UpdateMany(ctx,
bson.M{"instance_id": bson.M{"$exists": true}},