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

Express中Mongoose Populate无法关联查询关联集合问题排查

问题:Mongoose Populate 未返回关联的分类数据

我在Mongoose里创建了Category和Video两个集合,关联关系是Video通过cat_id关联到Category的_id,但用populate('categories')查询时,只返回了Video的数据,没拿到关联的分类详情,哪里错了?

我的Schema代码:

Category Schema

const categorySchema = new Schema({
  name:{ type:String, required:true },
  cat_type:{ type:String, enum:['images','quotes','videos'] },
  image:{ type:String },
  videoId:{ type:Number }
})
const Category = mongoose.model('categories',categorySchema);
module.exports = Category;

Video Schema

const videoSchema = new Schema({
  videoId:{ type:String },
  title:{ type:String, required:true },
  cat_id:{ type:Schema.Types.ObjectId, ref:'categories' },
  description:{ type:String },
  url:{ type:String },
  publishedAt:{ type:String }
})
const Video = mongoose.model('videos',videoSchema);
module.exports = Video;

我的查询代码:

Video.find({}).populate('categories').exec(function(err, data){
  console.log(data);
})

解答

嘿,问题出在populate()的参数上!你传的是集合名称categories,但Mongoose的populate()需要的是当前文档中存储关联ID的字段名,也就是Video Schema里的cat_id。

正确的查询代码:

Video.find({}).populate('cat_id').exec(function(err, data){
  if (err) {
    console.error('查询出错啦:', err);
    return;
  }
  console.log(data);
})

这样执行后,返回的每个Video对象里就会包含对应的Category数据,默认会把整个Category文档嵌在cat_id字段里。

进阶:自定义返回字段

如果你不想返回Category的所有字段,比如只需要name和cat_type,可以用对象配置来指定:

Video.find({})
  .populate({
    path: 'cat_id', // 关联字段名
    select: 'name cat_type -_id' // 要返回的字段,-_id表示排除_id
  })
  .exec(function(err, data){
    if (err) {
      console.error('查询出错:', err);
      return;
    }
    console.log(data);
  })

另外确认一下你的Category模型确实是用mongoose.model('categories', categorySchema)创建的,因为Video里的ref属性写的是'categories',这部分是对的,不用改~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:07:42