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

Mongoose使用populate关联Films集合仅返回ID无法获取name字段怎么解决

问题原因分析
  • Schema定义存在语法错误与配置错误:
    1. Recommendation的Schema配置参数拆分错误:mongoose.Schema的第二个参数为统一的配置对象,你将timestamps和_id: false拆分为两个独立对象传入,导致_id: false配置不生效;且字段必填属性拼写错误,应为required不是require
    2. Films的Schema存在语法错误,name字段定义结尾缺少逗号,会直接触发代码报错
  • Populate匹配规则错误:Mongoose默认使用当前字段值匹配目标模型的_id字段,但你的Recommendation.recommendation存储的是Films.id字段的值,并非Films._id,所以默认关联逻辑找不到对应文档,只能返回原ID值
  • 未指定返回字段,即便关联成功也会返回Films模型的全部字段,不符合仅返回id和name的需求
修复方案

1. 修正Schema定义

// Recommendation模型修正
const recommendationSchema = mongoose.Schema(
  {
    id_film: {
      type: Number,
      unique: true,
      required: true,
      trim: true,
    },
    recommendation: [{
      type: Number,
      ref: 'Films'
    }]
  }, 
  // 所有配置合并到同一个对象
  { timestamps: true, _id: false }
);
export const Recommendation = mongoose.model("Recommendations", recommendationSchema);

// Films模型修正
const filmsSchema = mongoose.Schema(
  {
    name: {
      type: String,
    }, // 补全缺失的逗号
    id: {
      type: Number,
      ref: 'Recommendations',
      unique: true // 可选配置,添加唯一索引提升关联查询效率
    },
  }
);
export const Films = mongoose.model("Films", filmsSchema);

2. 修正Populate查询逻辑

手动指定关联匹配字段和返回字段即可:

Recommendation.findOne({ id_film: req.params.id })
  .populate({
    path: 'recommendation',
    foreignField: 'id', // 指定用Films的id字段匹配,而非默认的_id
    select: 'id name -_id' // 仅返回id、name,去掉默认返回的_id字段,不需要可以删掉`-_id`
  })
  .exec(function (err, film) {
    if (err) return handleError(err);
    res.json(film);
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:45:03