You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB嵌套JSON字段验证失败:location.scraping_location必填错误排查

问题原因及解决方案

核心问题:字段拼写与映射完全不匹配

  • Schema定义的嵌套必填字段是 location.scraping_location(注意拼写为scraping)
  • 接口代码里错误写成了 scarping_location(少了字母r),同时请求体传递的是 location.location_scarping(字段名顺序颠倒+同样少r)
  • 这三重不匹配导致Mongoose无法找到必填的location.scraping_location字段,直接触发必填项验证错误

修正步骤

1. 修正接口代码中的字段映射

将接口里的location赋值部分改为正确的字段名:

const party = new Party({
    _id: new mongoose.Types.ObjectId(),
    title,
    datetime,
    location: { scraping_location: location.location_scarping }, // 修正字段名拼写
    picture,
    url,
    affiliate_url, 
    music_by,
    music_type,
    min_age_for_men,
    min_age_for_women,
    tags,
    producer_id
});

2. 规范请求体字段名(推荐)

让请求体的嵌套字段与Schema保持一致,避免后续混淆:

{
    "title": "test",
    "datetime": "2002-07-15T10:00:00+0300",
    "location": {
        "scraping_location": "new york" // 与Schema字段名统一
    },
    "picture": "test.jpg",
    "url": "https://google.com",
    "affiliate_url": "https://google.com",
    "min_age_for_men": 18,
    "min_age_for_women": 16
}

3. 可选:简化字段映射

如果请求体字段与Schema完全匹配,可直接传入整个location对象,无需手动解构:

const party = new Party({
    _id: new mongoose.Types.ObjectId(),
    title,
    datetime,
    location, // 直接传入完整location对象
    picture,
    url,
    affiliate_url, 
    music_by,
    music_type,
    min_age_for_men,
    min_age_for_women,
    tags,
    producer_id
});

内容的提问来源于stack exchange,提问作者Segev Solomon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:55:25