/** * employee.userId 唯一索引迁移。 * * 背景:employee.userId 之前是普通索引(字段级 index: true),同名索引 userId_1 * 已经在库里。现在 schema 改成 partial unique,MongoDB 不允许同一个键模式 * 同时存在不同选项的索引(IndexOptionsConflict / IndexKeySpecsConflict), * 必须先删旧索引再建新索引,否则 autoIndex 每次启动都会失败。 * * 步骤: * 1. 扫存量重复(userId 重复则中止,交人工裁决) * 2. 删除键模式为 { userId: 1 } 的旧索引(不论是否唯一) * 3. 建 { userId: 1 } 的 partial unique 索引(partial: userId 为 objectId, * 让历史 userId 为 null/缺失/字符串的脏数据不受约束) * * 用法(在 api/health 下): * node scripts/migrate_employee_userid_unique_index.js # 仅检查,不执行 * node scripts/migrate_employee_userid_unique_index.js --apply # 实际执行 */ import { DBModel } from "../models/index.js"; DBModel.init(); const conn = DBModel.dbConnection; const apply = process.argv.includes("--apply"); const INDEX_NAME = "userId_1"; const PARTIAL = { userId: { $type: "objectId" } }; async function main() { const db = conn.db; const employees = db.collection("employee"); // ---------- 1. 存量重复检查 ---------- const dupes = await employees .aggregate([ { $match: { userId: { $ne: null } } }, { $group: { _id: "$userId", n: { $sum: 1 }, ids: { $push: "$_id" } } }, { $match: { n: { $gt: 1 } } }, ]) .toArray(); if (dupes.length) { console.log(`发现 ${dupes.length} 组 userId 重复,无法建唯一索引,请先人工处理:`); for (const dupe of dupes) { const docs = await employees .find({ userId: dupe._id }) .project({ role: 1, status: 1, name: "$profile.name", createtime: "$meta.createtime" }) .toArray(); console.log(` userId=${dupe._id} x${dupe.n}`); for (const doc of docs) { console.log( ` - ${doc._id} role=${doc.role} status=${doc.status} name=${doc.name || "-"} created=${doc.createtime || "-"}` ); } } console.log("\n处理建议:保留 status=active 且创建时间最新的一条,其余改 userId: null 或删除。"); return; } console.log("userId 重复检查:无重复,可安全建唯一索引"); // ---------- 2. 删除旧索引 ---------- const indexes = await employees.indexes(); const old = indexes.find( (idx) => JSON.stringify(idx.key) === JSON.stringify({ userId: 1 }) ); if (old) { const isTarget = old.unique === true && JSON.stringify(old.partialFilterExpression) === JSON.stringify(PARTIAL); if (isTarget) { console.log(`索引 ${old.name} 已是目标形态(partial unique),无需变更`); return; } console.log( `待删除旧索引 ${old.name}(unique=${!!old.unique}, partial=${JSON.stringify(old.partialFilterExpression || null)})` ); if (!apply) { console.log("dry-run:加 --apply 执行删除"); return; } await employees.dropIndex(old.name); console.log(`已删除 ${old.name}`); } else { console.log("未发现 { userId: 1 } 旧索引,跳过删除"); } // ---------- 3. 建 partial unique ---------- if (!apply) { console.log("dry-run:加 --apply 创建 partial unique 索引"); return; } await employees.createIndex({ userId: 1 }, { unique: true, partialFilterExpression: PARTIAL, name: INDEX_NAME }); console.log(`已创建 ${INDEX_NAME}:{ userId: 1 } unique + partial(userId 为 objectId)`); } if (conn.readyState === 1) { main() .catch((e) => { console.error(e); process.exitCode = 1; }) .finally(() => conn.close()); } else { conn.once("connected", () => main() .catch((e) => { console.error(e); process.exitCode = 1; }) .finally(() => conn.close()) ); conn.once("error", (e) => { console.error(e); process.exit(1); }); }