简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z 使用默认选定字段填充虚拟

[英]Mongoose populate virtual with default selected fields

I have this virtual in a mongoose schema:我在 mongoose 架构中有这个虚拟:

PostSchema.virtual("author", {
    ref: "User",
    localField: "userId",
    foreignField: "_id",
    justOne : true,
});

and when i call .find() , I can populate it like this:当我调用.find()时,我可以像这样填充它:

PostSchema.find(...).populate("author", "displayName username avatar")

As you can see I only selected some fields to populate into author , this works fine and gives me the result that I want.如您所见,我只选择了一些字段来填充author ,这很好用,并给了我想要的结果。

But is it possible to set the default selected fields when creating a virtual on my Schema?但是在我的架构上创建虚拟时是否可以设置默认选定字段? Probably something like this:大概是这样的:

PostSchema.virtual("author", {
    ref: "User",
    localField: "userId",
    foreignField: "_id",
    justOne : true,
    fields: "displayName username avatar"
});

so I don't have to put selected fields on the 2nd parameter every time I call populate.所以我不必每次调用填充时都将选定的字段放在第二个参数上。

PostSchema.find(...).populate("author")
// `author` still will only contains displayName, username, and avatar, not the whole fields from User schema

You can define a function on your User schema, which returns only specific fields you want:您可以在您的User架构上定义 function,它只返回您想要的特定字段:

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

And then you can define mongoose post middleware of your find in your post schema which will be triggered after data is fetch from the db:然后你可以定义 mongoose 在你的 post 模式中找到的post中间件,这将在从 db 获取数据后触发:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM