/** * 只读补查:孤儿 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); }); }