【问题标题】:How to populate mongoose virtual from another referenced model?如何从另一个参考模型填充猫鼬虚拟?
【发布时间】:2021-09-19 23:15:43
【问题描述】:
 // define a schema
  const personSchema = new Schema({
    name: {
      first: String,
      last: String
    }
  },
  {
    toJSON: {
      virtuals: true,
    },
    toObject: {
      virtuals: true,
    },
  },);
personSchema.virtual('fullName').
  get(function() {
    return this.name.first + ' ' + this.name.last;
    }).
  set(function(v) {
    this.name.first = v.substr(0, v.indexOf(' '));
    this.name.last = v.substr(v.indexOf(' ') + 1);
  });

  // compile our model
  const Person = mongoose.model('Person', personSchema);

这是从文档中定义#virtuals

让我们有另一个引用 Person 的模型:

 const shopSchema = new Schema({
    name:String,
    owner: { type: Schema.Types.ObjectId, ref: "Person" },
  });
const Shop = mongoose.model('Shop', shopSchema);

现在,如何在商店中获取 fullName virtuals 填充 owner。这里,所有者不包括fullName

const getAllData = async () => {
     const shops = await Shop.find().populate("owner").lean();
     console.log(shops)
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    根据mongoose docs

    使用 lean() 绕过所有 Mongoose 功能,包括虚拟、getter/setter 和默认值。如果你想通过lean()来使用这些特性,你需要使用相应的插件。

    因此,fullName 已从返回的数据中删除。获取fullName virtuals 的简单方法是将查询更改为以下内容:

    const getAllData = async () => {
      const shops = await Shop.find()
        .populate({
          path: 'owner',
          options: {
            lean: false
          }
        })
        .lean();
      console.log(shops);
    };
    

    它不会在populate 中使用lean(),或者您可以完全禁用lean()

    【讨论】:

      猜你喜欢
      • 2021-01-09
      • 2017-09-13
      • 2017-04-04
      • 2020-11-30
      • 2015-01-13
      • 2020-05-18
      • 2021-04-24
      • 2020-11-02
      • 2021-06-29
      相关资源
      最近更新 更多