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

如何在Mongoose中填充关联Profile模型的User嵌套数据?

问题:如何将dataSubmitted中的user ID关联填充至profile模型?

现有模型定义

dataSubmitted模型

module.exports = (mongoose, mongoosePaginate) => {
  const schema = mongoose.Schema({
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    company: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
  }, {
    timestamps: true
  })

  schema.plugin(mongoosePaginate)

  const dataSubmitted = mongoose.model('dataSubmitted', schema)

  return dataSubmitted
}

Profile模型

module.exports = (mongoose, mongoosePaginate) => {
  const schema = mongoose.Schema({
    name: String,
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
  }, {
    timestamps: true
  })

  schema.plugin(mongoosePaginate)

  const profile = mongoose.model('profile', schema)

  return profile
}

当前查询结果示例

{
  "totalItems": 90,
  "data": [
    {
      "_id": "63546cb05bfb8607c005da6a",
      "user": "6353a1aebaf28d7aa066a963",
      "company": "6022487bbe148f3a9b132122",
      "createdAt": "2022-10-22T22:20:32.296Z",
      "updatedAt": "2022-10-25T07:09:52.363Z",
      "__v": 0
    }
  ]
}

当前尝试的无效代码

const options = {
    populate: [
      {
        path: 'user',
        populate: {
          path: 'user',
          model: 'profile'
        }
      }
    ],
    sort: ({ createdAt: -1 })
  }

问题原因

你之前的嵌套填充逻辑错误:dataSubmitted的user字段关联的是User模型,但你试图从User模型中填充不存在的user字段(User模型里没有定义指向Profile的user字段),所以返回null。实际关联关系是dataSubmitted -> User <- Profile,而非dataSubmitted -> User -> Profile,无法用这种嵌套填充方式。

解决方法

方法1:使用Aggregate + $lookup(无需修改现有模型,推荐)

利用MongoDB的$lookup关联查询,直接通过dataSubmitted的user(即User的ID)匹配Profile中对应的user字段:

const options = {
  aggregate: [
    {
      $lookup: {
        from: 'profiles', // 对应Profile模型的集合名(mongoose默认生成模型名小写复数)
        localField: 'user', // dataSubmitted中的user字段(User的ID)
        foreignField: 'user', // Profile中关联User的字段
        as: 'userProfile' // 存储匹配到的Profile的字段名
      }
    },
    // 如果每个用户仅对应一个Profile,展开数组;允许多个则移除该步骤
    { $unwind: { path: '$userProfile', preserveNullAndEmptyArrays: true } }
  ],
  sort: { createdAt: -1 },
  // 添加分页参数如page、limit等
};

// 调用分页查询
const result = await dataSubmitted.paginate({}, options);

查询结果中,每个data项会新增userProfile字段,包含对应的Profile文档。

方法2:修改User模型添加Profile引用(需维护关联)

如果允许修改User模型,添加指向Profile的引用字段:

// 在User模型的Schema中新增
profile: {
  type: mongoose.Schema.Types.ObjectId,
  ref: 'profile'
}

注意:需要在创建/更新Profile时同步更新User的profile字段,确保关联关系有效。之后可使用嵌套填充:

const options = {
  populate: [
    {
      path: 'user',
      populate: {
        path: 'profile',
        model: 'profile'
      }
    }
  ],
  sort: { createdAt: -1 }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:10:26