假设我具有以下架构:
用户
const UserSchema: Schema = new Schema(
{
name: String,
phoneNumbers: [ ... ],
}
);
const autoPopulateFields = function (next: HookNextFunction) {
this.populate('phoneNumbers');
next();
};
const User = mongoose.model<IComment>("User", UserSchema);
export default User;
评论
const CommentSchema: Schema = new Schema(
{
body: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
}
);
const autoPopulateFields = function (next: HookNextFunction) {
this.populate('author');
next();
};
CommentSchema.pre('findOne', autoPopulateFields).pre('find', autoPopulateFields);
const Comment = mongoose.model<IComment>("Comment", CommentSchema);
export default Comment;
父母
const ParentSchema: Schema = new Schema(
{
body: String,
comments: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment', required: false }
]
}
);
const Parent = mongoose.model<IParent>("Parent", ParentSchema);
export default Parent;
在文件中,我正在查找父对象,但我希望在一个填充语句中取消选择作者> phoneNumber(我知道我可以在模式中做到这一点,但是有一种方法可以覆盖子对象填充东西?)。
我尝试了通常的嵌套填充,但在这种情况下似乎不起作用:
Parent.findById(id)
.populate({
path: 'comments',
populate: {
path: 'author',
model: 'User',
select: '-phoneNumbers'
}
})
有什么想法吗?