Mongoose跨层级populate时如何限制嵌套层级仅返回指定字段
要限制嵌套层级populate返回的字段,只需在对应层级的populate配置中添加select属性,指定需要返回的字段即可,修改后的代码如下:
const userSchema = new Schema({ name: String, email: String, friends: [{ type: ObjectId, ref: 'User' }] }); User. findOne({ name: 'Val' }). populate({ path: 'friends', // 若需要同时限制第一层friends的返回字段,可在当前层级加select配置,示例:select: 'name email' populate: { path: 'friends', select: 'name' // 仅返回嵌套层级friends的name字段 // 若不需要默认返回的_id字段,可改为 select: 'name -_id' } });
补充说明:多层嵌套populate的字段限制逻辑统一,每一级的populate配置都可以通过独立的select属性控制当前层级关联数据的返回字段。
内容的提问来源于stack exchange,提问作者Manish Kumar
相关产品推荐
相关产品推荐

