猫鼬用默认选择的字段填充虚拟

时间:2020-07-16 08:36:33

标签: javascript node.js 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

1 个答案:

答案 0 :(得分:0)

您可以在User模式中定义一个函数,该函数仅返回您想要的特定字段:

UserSchema.method('getAuthorFields', function () {
  return {
    displayName: this.displayName,
    username: this.username,
    avatar: this.avatar
  }
})

然后您可以在发布架构中定义猫鼬post中间件,该中间件将在从db中获取数据后触发:

PostSchema.post('init', function () {
    this.author = this.author.getAuthorFields();
});