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

如何在Mongoose中对ObjectId数组字段执行选择性Populate查询

Mongoose关联查询:Populate数组字段并指定返回字段

1. 关联字段Schema定义

以下是Response模型中friends字段的Schema配置,该字段用于存储关联的User文档ObjectId数组,且限制最多包含3个元素:

friends: {
    type: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }],
    required: false,
    validate: [arrayLimit, '{PATH} exceeds the limit of 3']
  }

2. 执行查询并指定Populate返回字段

要查询所有Response文档,并对friends字段进行关联查询(Populate),同时仅返回关联User文档的name和username字段,可以使用以下代码:

const responses = await Response.find({}).populate("friends", {name: 1, username: 1})

这段代码会自动将friends数组中的每个ObjectId替换为对应的User文档实例,且只保留name和username两个字段,其他字段不会被返回。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:17:03