如何在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
相关产品推荐
相关产品推荐

