fix: 健康档案更新摊平嵌套对象避免 Mongo 路径冲突

$set 同时出现 profile 与 profile.pinyin 会触发路径冲突,
整块覆盖嵌套对象又绕开 pre("save") 丢拼音字段;
pickFields 支持 flatten 递归摊平后按点号路径写入
This commit is contained in:
lik
2026-11-08 12:00:25 +08:00
parent 5878520707
commit b386dc469f
+30 -9
View File
@@ -66,18 +66,36 @@ class HandlerHealthProfile {
/**
* 按白名单挑选字段(支持 "profile.name" 这类点号路径)
*
* flatten=true 时把嵌套对象摊平成点号路径,供更新接口使用:
* $set 同时出现 profile 与 profile.pinyin 会触发 Mongo 路径冲突,
* 而整块覆盖 profile 又会绕开 pre("save") 导致拼音字段丢失。
*
* @param {Object} body 请求体
* @param {Object} [options]
* @param {boolean} [options.flatten] 是否摊平嵌套对象
* @returns {Object}
*/
static pickFields(body) {
static pickFields(body, { flatten = false } = {}) {
const picked = {};
for (const key of Object.keys(body || {})) {
const allowed = HandlerHealthProfile.PROFILE_FIELDS.some(
(f) => key === f || key.startsWith(f + ".")
);
if (allowed) {
picked[key] = body[key];
const allowed = (path) => HandlerHealthProfile.PROFILE_FIELDS.some(
(f) => path === f || path.startsWith(f + ".")
);
const walk = (value, path) => {
if (!allowed(path)) return;
const isPlainObject = value !== null && typeof value === "object"
&& !Array.isArray(value) && !(value instanceof Date);
if (flatten && isPlainObject) {
for (const [key, child] of Object.entries(value)) {
walk(child, `${path}.${key}`);
}
return;
}
picked[path] = value;
};
for (const [key, value] of Object.entries(body || {})) {
walk(value, key);
}
return picked;
}
@@ -236,7 +254,7 @@ class HandlerHealthProfile {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}
const update = HandlerHealthProfile.pickFields(ctx.request.body);
const update = HandlerHealthProfile.pickFields(ctx.request.body, { flatten: true });
delete update.userId; // 不允许通过请求转移档案归属
const invalid = HandlerHealthProfile.validateProfileInput(update);
@@ -319,7 +337,10 @@ class HandlerHealthProfile {
return ResponseUtil.badRequest(ctx, "缺少档案ID");
}
const updatedProfile = await DBModel.HealthProfile.updateProfileById(id, HandlerHealthProfile.pickFields(update));
const updatedProfile = await DBModel.HealthProfile.updateProfileById(
id,
HandlerHealthProfile.pickFields(update, { flatten: true })
);
if (!updatedProfile) {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}