我正在使用以下模型架构:
var AppointmentSchema = new Schema({
appointment_date: {type: Date},
created: {
type: Date,
default: Date.now
},
updated: {type: Date},
client: [{ type: Schema.Types.ObjectId, ref: 'User' }],
staff_id: [{ type: Schema.Types.ObjectId, ref: 'User' }],
cost:{
type: Number
},
jobDone:{
type: Boolean,
default: false
},
cancelled:{
type: Boolean,
default: false
}
});
其中明确引用了用户模型。
当我查询时,我想填充客户端和员工数据,但没有他们在该模型中保存的某些字段。
因此,如果用户模型是:
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
}
});
我只想填充firstName和email(并省略其余的)可能吗?
答案 0 :(得分:1)
要返回为 populated 文档返回的一些特定字段,您需要将通常的field name syntax作为第二个参数传递给populate方法:
Appointment
.findOne({ cancelled: true })
.populate('client', 'firstName displayName') // only return the User's firstName and displayName
.exec(function (err, appointment) {
if (err) return handleError(err);
console.log('The client name is %s', appointment.client.firstName);
// prints "The client name is Aaron"
console.log('The client display name is %s', appointment.client.displayName);
// prints "The client display name is aarontest'
})