From b386dc469f678bed44da41e28ecdddf5f28db161 Mon Sep 17 00:00:00 2001 From: lik Date: Sun, 8 Nov 2026 12:00:25 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=81=A5=E5=BA=B7=E6=A1=A3=E6=A1=88?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=91=8A=E5=B9=B3=E5=B5=8C=E5=A5=97=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E9=81=BF=E5=85=8D=20Mongo=20=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit $set 同时出现 profile 与 profile.pinyin 会触发路径冲突, 整块覆盖嵌套对象又绕开 pre("save") 丢拼音字段; pickFields 支持 flatten 递归摊平后按点号路径写入 --- handler/health_profile.js | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/handler/health_profile.js b/handler/health_profile.js index d32f265..46210c1 100644 --- a/handler/health_profile.js +++ b/handler/health_profile.js @@ -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, "健康档案不存在"); }