chore(schema): organization 移除医院相关定义并留档数据清理脚本
医院数据统一走 hospital 集合后,organization 移除 hospital 枚举、 level 与就医信息字段(overview/photos/departments/doctors/guides)。 新增一次性清理脚本(删医院记录、删 2026-11 前订单)与只读体检脚本 (索引同步、孤儿引用、脏数据检查)。
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 只读体检:对比 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); });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* 只读补查:孤儿 payment_record 明细 + user/users 集合归属确认。
|
||||
* 用法(在 api/health 下):node scripts/check_orphan_payments.js
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
async function main() {
|
||||
const db = conn.db;
|
||||
|
||||
// 找出 recordId 在 escort_record 中不存在的 payment_record
|
||||
const orphanPayments = await db.collection("payment_record").aggregate([
|
||||
{ $match: { recordId: { $ne: null } } },
|
||||
{ $lookup: { from: "escort_record", localField: "recordId", foreignField: "_id", as: "hit" } },
|
||||
{ $match: { hit: { $size: 0 } } },
|
||||
]).toArray();
|
||||
|
||||
console.log(`orphan payment_record docs: ${orphanPayments.length}`);
|
||||
for (const p of orphanPayments) {
|
||||
console.log(` ${p._id} outTradeNo=${p.outTradeNo} status=${p.status} totalFee=${p.totalFee} payerTotal=${p.payerTotal} userId=${p.userId} createdAt=${p.createdAt?.toISOString?.() ?? p.createdAt}`);
|
||||
const refunds = await db.collection("refund_record").find({ paymentId: p._id }).toArray();
|
||||
refunds.forEach((r) => console.log(` refund: ${r._id} outRefundNo=${r.outRefundNo} status=${r.status} amount=${r.refundAmount}`));
|
||||
}
|
||||
|
||||
// user / users 集合情况
|
||||
for (const name of ["user", "users"]) {
|
||||
const exists = await db.listCollections({ name }).hasNext();
|
||||
if (!exists) {
|
||||
console.log(`\ncollection ${name}: NOT EXIST`);
|
||||
continue;
|
||||
}
|
||||
const n = await db.collection(name).countDocuments({});
|
||||
const sample = await db.collection(name).findOne({}, { projection: { mobile: 1, phone: 1, name: 1, nickname: 1, createdAt: 1, "meta.createtime": 1 } });
|
||||
console.log(`\ncollection ${name}: ${n} docs, sample=${JSON.stringify(sample)}`);
|
||||
}
|
||||
|
||||
// 现存 escort_record 的 userId 是否在 users 里能对上
|
||||
const records = await db.collection("escort_record").find({}, { projection: { userId: 1 } }).toArray();
|
||||
for (const r of records) {
|
||||
const inUsers = r.userId ? await db.collection("users").countDocuments({ _id: r.userId }) : 0;
|
||||
console.log(`escort_record ${r._id} userId=${r.userId} in users: ${inUsers}`);
|
||||
}
|
||||
|
||||
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); });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 一次性清理:物理删除 escort_record(陪诊订单)里 2026-11-01 之前创建的记录。
|
||||
*
|
||||
* 注意:已确认要全删(含已支付/已完成订单),不受「已收款订单需留存审计」的常规约束。
|
||||
* 时间口径:meta.createtime < 2026-11-01 00:00:00(Asia/Shanghai)。
|
||||
*
|
||||
* 用法(在 api/health 下):
|
||||
* node scripts/delete_escort_records_before_202611.js # 仅统计,不删除
|
||||
* node scripts/delete_escort_records_before_202611.js --apply # 实际删除
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
const apply = process.argv.includes("--apply");
|
||||
|
||||
// 东八区 2026-11-01 00:00:00,避免服务器时区差异
|
||||
const CUTOFF = new Date("2026-11-01T00:00:00+08:00");
|
||||
const filter = { "meta.createtime": { $lt: CUTOFF } };
|
||||
|
||||
async function cleanup() {
|
||||
const matched = await DBModel.EscortRecord.countDocuments(filter).exec();
|
||||
const byStatus = await DBModel.EscortRecord.aggregate([
|
||||
{ $match: filter },
|
||||
{ $group: { _id: "$status", count: { $sum: 1 } } },
|
||||
]).exec();
|
||||
|
||||
console.log(`cutoff=${CUTOFF.toISOString()} (2026-11-01 00:00:00 +08:00)`);
|
||||
console.log(`matched escort records created before cutoff: ${matched}`);
|
||||
byStatus.forEach((row) => console.log(` status=${row._id ?? "none"}: ${row.count}`));
|
||||
|
||||
if (!apply) {
|
||||
console.log("dry-run only. re-run with --apply to delete.");
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await DBModel.EscortRecord.deleteMany(filter);
|
||||
console.log(`deleted: ${result.deletedCount}`);
|
||||
}
|
||||
|
||||
cleanup()
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => {
|
||||
conn.close();
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 一次性清理:删除 organization 集合里医院相关的记录。
|
||||
*
|
||||
* 医院基础信息已统一迁移到 hospital 集合(schema/hospital.js),
|
||||
* organization 集合不再维护医院数据;本脚本删除 type=hospital 的记录。
|
||||
*
|
||||
* 用法:在 api/health 下执行 `node scripts/delete_organization_hospitals.js`
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
async function cleanup() {
|
||||
// 非医院记录(历史数据里可能有未填 type 的)统一保留,只删明确标记为医院的
|
||||
const filter = { type: "hospital" };
|
||||
const matched = await DBModel.Organization.countDocuments(filter).exec();
|
||||
const result = await DBModel.Organization.deleteMany(filter);
|
||||
|
||||
console.log(`deleted: matched=${matched}, deletedCount=${result.deletedCount}`);
|
||||
const remaining = await DBModel.Organization.countDocuments({}).exec();
|
||||
console.log(`remaining organizations: ${remaining}`);
|
||||
await conn.close();
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
cleanup().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
conn.once("connected", () => {
|
||||
cleanup().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
conn.once("error", (error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user