/** * 只读体检:对比 models/schema 定义与实际 MongoDB,不做任何写操作。 * * 检查项: * 1. 实际集合 vs 已注册模型(多出的集合 / 缺失的集合) * 2. 每个模型:schema 声明的索引 vs 数据库实际索引(缺的 / 多的) * 3. 各集合文档数 * 4. 跨集合孤儿引用(删除订单后的 payment/refund 残留、employee.orgId、healthProfileId 等) * 5. 明显脏数据(旧式 status=cancelled、缺失 cancelStatus、organization 残留医院字段) * * 用法(在 api/health 下):node scripts/check_db_schema_sync.js */ import { DBModel } from "../models/index.js"; import mongoose from "mongoose"; DBModel.init(); const conn = DBModel.dbConnection; const report = (title, rows) => { console.log(`\n===== ${title} =====`); if (!rows.length) { console.log(" (none)"); return; } rows.forEach((row) => console.log(` ${row}`)); }; const keyOf = (indexDef) => JSON.stringify(indexDef); async function main() { const db = conn.db; // ---------- 1. 集合 vs 模型 ---------- const collections = (await db.listCollections().toArray()).map((c) => c.name); const modelNames = conn.modelNames(); // 小写 collection 名 report("1. collections in DB but no model", collections.filter((c) => !modelNames.includes(c))); report("1. models without collection in DB", modelNames.filter((m) => !collections.includes(m))); // ---------- 2/3. 索引与文档数 ---------- for (const name of modelNames) { const model = conn.model(name); const actual = await db.collection(name).indexes(); // schema.indexes() 返回 [ [indexDef, options], ... ],第一个元素才是键定义 const expected = [{ key: { _id: 1 } }, ...model.schema.indexes().map(([def]) => ({ key: def }))]; const actualKeys = new Set(actual.map((idx) => keyOf(idx.key))); // 模型里声明的但库里没有的 const missing = expected.filter((idx) => !actualKeys.has(keyOf(idx.key))); // 额外声明:unique/sparse/partial 选项差异只提示名字,人工确认 const expectedKeys = new Set(expected.map((idx) => keyOf(idx.key))); const extra = actual.filter((idx) => !expectedKeys.has(keyOf(idx.key))); const count = await db.collection(name).countDocuments({}); console.log(`\n===== ${name} =====`); console.log(` docs: ${count}`); if (missing.length) console.log(` MISSING indexes (in schema, not in DB): ${missing.map((m) => keyOf(m.key)).join(", ")}`); if (extra.length) console.log(` EXTRA indexes (in DB, not in schema): ${extra.map((e) => `${keyOf(e.key)}${e.unique ? " [unique]" : ""}${e.sparse ? " [sparse]" : ""}${e.partialFilterExpression ? " [partial]" : ""}`).join(", ")}`); if (!missing.length && !extra.length) console.log(" indexes: in sync"); } // ---------- 4. 孤儿引用 ---------- const orphans = async (label, fromColl, fromField, toColl, detail = null) => { const rows = await db.collection(fromColl).aggregate([ { $match: { [fromField]: { $ne: null } } }, { $group: { _id: `$${fromField}` } }, { $lookup: { from: toColl, localField: "_id", foreignField: "_id", as: "hit" } }, { $match: { hit: { $size: 0 } } }, { $count: "n" }, ]).toArray(); if (!rows.length) { report(`4. orphan ${fromColl}.${fromField} -> ${toColl}`, []); return; } let lines = [` ${rows[0].n} distinct missing refs`]; if (detail) { const missingIds = await db.collection(fromColl).aggregate([ { $match: { [fromField]: { $ne: null } } }, { $group: { _id: `$${fromField}` } }, { $lookup: { from: toColl, localField: "_id", foreignField: "_id", as: "hit" } }, { $match: { hit: { $size: 0 } } }, { $project: { _id: 1 } }, ]).toArray(); const idSet = new Set(missingIds.map((d) => String(d._id))); const docs = await db.collection(fromColl).find({ [fromField]: { $in: [...idSet] } }).toArray(); lines = lines.concat(docs.map((d) => detail(d))); } report(`4. orphan ${fromColl}.${fromField} -> ${toColl}`, lines); }; await orphans( "payment_record.recordId", "payment_record", "recordId", "escort_record", (d) => ` ${d._id} outTradeNo=${d.outTradeNo} status=${d.status} totalFee=${d.totalFee} createdAt=${d.createdAt?.toISOString?.() ?? d.createdAt}` ); await orphans("refund_record.recordId", "refund_record", "recordId", "escort_record"); await orphans("refund_record.paymentId", "refund_record", "paymentId", "payment_record"); await orphans("escort_record.healthProfileId", "escort_record", "healthProfileId", "health_profile"); await orphans("employee.orgId", "employee", "orgId", "organization"); await orphans("employee_review.recordId", "employee_review", "recordId", "escort_record"); await orphans("employee_review.employeeId", "employee_review", "employeeId", "employee"); await orphans("escort_record.paymentRecordId", "escort_record", "paymentRecordId", "payment_record"); // ---------- 5. 脏数据 ---------- const dirty = []; const cnt = async (label, filter, coll) => { const n = await db.collection(coll).countDocuments(filter); if (n > 0) dirty.push(`${coll}: ${label} = ${n}`); }; await cnt("status=cancelled(旧式取消写法)", { status: "cancelled" }, "escort_record"); await cnt("缺少 cancelStatus 字段", { cancelStatus: { $exists: false } }, "escort_record"); await cnt("type=hospital(应已清理)", { type: "hospital" }, "organization"); await cnt("残留 forAgent 字段", { forAgent: { $exists: true } }, "organization"); // hospital name 唯一索引是否真生效:查重复名 const dupNames = await db.collection("hospital").aggregate([ { $group: { _id: "$name", n: { $sum: 1 } } }, { $match: { n: { $gt: 1 } } }, { $limit: 10 }, ]).toArray(); if (dupNames.length) dirty.push(`hospital: 重复 name = ${dupNames.map((d) => `${d._id}(${d.n})`).join(", ")}`); // organization 残留医院专属字段 const orgHospitalFields = await db.collection("organization").countDocuments({ $or: [ { overview: { $exists: true } }, { photos: { $exists: true } }, { departments: { $exists: true } }, { doctors: { $exists: true } }, { guides: { $exists: true } }, { level: { $exists: true } }, ], }); if (orgHospitalFields > 0) dirty.push(`organization: 残留医院字段文档 = ${orgHospitalFields}`); // user 集合存在性(多模型 ref user) if (!collections.includes("user")) dirty.push("user 集合不存在,但多张表 ref user"); report("5. dirty/stale data", dirty.map((d) => d.replace(/^/, ""))); console.log("\n(check done, read-only)"); } 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); }); }