[英]Mongoose populate virtual with default selected fields
我在 mongoose 架构中有这个虚拟:
PostSchema.virtual("author", {
ref: "User",
localField: "userId",
foreignField: "_id",
justOne : true,
});
当我调用.find()
时,我可以像这样填充它:
PostSchema.find(...).populate("author", "displayName username avatar")
如您所见,我只选择了一些字段来填充author
,这很好用,并给了我想要的结果。
但是在我的架构上创建虚拟时是否可以设置默认选定字段? 大概是这样的:
PostSchema.virtual("author", {
ref: "User",
localField: "userId",
foreignField: "_id",
justOne : true,
fields: "displayName username avatar"
});
所以我不必每次调用填充时都将选定的字段放在第二个参数上。
PostSchema.find(...).populate("author")
// `author` still will only contains displayName, username, and avatar, not the whole fields from User schema
您可以在您的User
架构上定义 function,它只返回您想要的特定字段:
UserSchema.method('getAuthorFields', function () {
return {
displayName: this.displayName,
username: this.username,
avatar: this.avatar
}
})
然后你可以定义 mongoose 在你的 post 模式中找到的post
中间件,这将在从 db 获取数据后触发:
PostSchema.post('init', function () {
this.author = this.author.getAuthorFields();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.