83 lines
2.4 KiB
JavaScript
83 lines
2.4 KiB
JavaScript
/**
|
|
* 一次性回填/迁移:把复旦榜信息写成 fudanRank: { rank, grade, order }。
|
|
*
|
|
* 用法:在 api/health 下执行 `node scripts/backfill_hospital_fudan_rank.js`
|
|
* 未上榜医院写默认档位 999 / 默认顺序 9999,保证接口排序时排在所有上榜医院之后。
|
|
* 脚本同时清理旧的扁平字段 fudanGrade / fudanOrder。
|
|
*/
|
|
import { DBModel } from "../models/index.js";
|
|
import {
|
|
DEFAULT_FUDAN_RANK,
|
|
DEFAULT_FUDAN_ORDER,
|
|
resolveFudanRank,
|
|
} from "../models/schema/hospital.js";
|
|
|
|
DBModel.init();
|
|
const conn = DBModel.dbConnection;
|
|
|
|
async function backfill() {
|
|
// 存量文档可能是旧的扁平字段,直接用原生 collection 读取,避免新旧 schema 互转
|
|
const rawCollection = conn.db.collection("hospital");
|
|
const hospitals = await rawCollection.find(
|
|
{},
|
|
{ projection: { name: 1, entityName: 1, fudanRank: 1, fudanGrade: 1, fudanOrder: 1 } }
|
|
).toArray();
|
|
|
|
const operations = [];
|
|
let ranked = 0;
|
|
|
|
for (const hospital of hospitals) {
|
|
const fudan = resolveFudanRank([hospital.entityName, hospital.name]);
|
|
const rank = fudan ? fudan.rank : DEFAULT_FUDAN_RANK;
|
|
const grade = fudan ? fudan.grade : "";
|
|
const order = fudan ? fudan.order : DEFAULT_FUDAN_ORDER;
|
|
if (fudan) ranked += 1;
|
|
|
|
const current = hospital.fudanRank;
|
|
const isNested = current && typeof current === "object";
|
|
const unchanged = isNested
|
|
&& current.rank === rank
|
|
&& current.grade === grade
|
|
&& current.order === order;
|
|
const hasLegacyFields = hospital.fudanGrade !== undefined || hospital.fudanOrder !== undefined;
|
|
if (unchanged && !hasLegacyFields) continue;
|
|
|
|
operations.push({
|
|
updateOne: {
|
|
filter: { _id: hospital._id },
|
|
update: {
|
|
$set: { fudanRank: { rank, grade, order } },
|
|
$unset: { fudanGrade: "", fudanOrder: "" },
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
if (operations.length > 0) {
|
|
await rawCollection.bulkWrite(operations);
|
|
}
|
|
|
|
console.log(
|
|
`backfilled: total=${hospitals.length}, ranked=${ranked}, updated=${operations.length}`
|
|
);
|
|
await conn.close();
|
|
}
|
|
|
|
if (conn.readyState === 1) {
|
|
backfill().catch((error) => {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|
|
} else {
|
|
conn.once("connected", () => {
|
|
backfill().catch((error) => {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|
|
});
|
|
conn.once("error", (error) => {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|
|
}
|