如何在Mongoose populate关联查询中仅返回指定字段子集
Mongoose关联查询仅返回指定字段实现方案
问题说明
使用Mongoose的ref功能填充关联集合数据时,默认查询会返回关联文档的全部字段,如需仅返回指定字段可按以下方案调整。
现有代码参考
1. 存储关联ObjectId的集合Schema
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const StaticAssignmentSchema = new Schema({ affiliation: { type: String }, REF_person: [{ type: Schema.Types.ObjectId, ref: 'users' }], }); module.exports = StaticAssignmentNew = mongoose.model('staticassignments', StaticAssignmentSchema);
2. 用户集合Schema
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ name: { type: String }, phone: { type: String }, password: { type: String }, affiliation: { type: String }, timezone: { type: String }, date: { type: Date, default: Date.now }, }); module.exports = User = mongoose.model('users', UserSchema);
3. 原查询代码
var query = { affiliation: affiliation }; var ret = await StaticAssignment.findOne(query).populate('REF_person');
调整后实现方案
将populate方法的入参改为配置对象,通过select属性指定需要返回的字段即可:
var query = { affiliation: affiliation }; var ret = await StaticAssignment.findOne(query) .populate({path: 'REF_person', select: '_id name phone'});
参数说明
path:指定要填充的关联字段名,此处对应Schema中定义的REF_personselect:空格分隔的字段列表,列出所有需要返回的字段;如果需要排除某字段可在字段名前加-,比如不需要_id可写为-_id name phone
内容的提问来源于stack exchange,提问作者MrLister
相关产品推荐
相关产品推荐

