【问题标题】:Can't get mongoose virtual populate up and running in NestJS app无法在 NestJS 应用程序中启动并运行猫鼬虚拟填充
【发布时间】:2021-05-05 19:13:39
【问题描述】:

我目前正在开展一个非常需要虚拟填充的项目:

有一个客户方案、一个文档方案以及其他一些引用客户的方案。在客户内部,我想填充引用的项目。

我已经有一个使用 Typegoose 的工作模型,由于后期不兼容,我不得不从项目中删除它。 之前是这样工作的:

  @prop({ 
    ref: () => DMSDocument,
    foreignField: 'linkedCustomers', // compare this value to the local document populate is called on
    localField: '_id', // compare this to the foreign document's value defined in "foreignField",
    justOne: false
  })
  public documents: { type: Types.ObjectId, ref: 'DMSDocument' }[];

现在我只是在删除 typegoose 之后才尝试使用 nestjs/mongoose 来实现这一点:

@Prop({ 
    virtual: 'documents',
    ref: 'DMSDocument',
    foreignField: 'linkedCustomers',
    localField: '_id',
  })
  public documents: DMSDocument[];

虚拟吸气剂工作得很好,因为我只是在使用

@Schema({ toJSON: { virtuals: true, getters: true }, toObject: { virtuals: true, getters: true }})

模型是这样填充的:

this.customerModel.findOne(params)
.populate('documents', '', 'DMSDocument')
.populate('repairs', '', 'Repair')

我不知何故被卡住了 - 我只是得到空数组,没有错误。我错过了什么?他们甚至可以使用nestjs/mongoose吗?

【问题讨论】:

    标签: mongoose nestjs mongoose-populate


    【解决方案1】:

    好的,我设法让事情恢复正常,但不是以首选方式:

    在定义类并将其转换为架构之后

    export const CustomerSchema = SchemaFactory.createForClass(Customer);
    

    我只需要“手动”添加虚拟填充:

    CustomerSchema.virtual('documents', {
      ref: 'DMSDocument',
      localField: '_id',
      foreignField: 'links.customers',
      justOne: false
    }); 
    

    一切都按预期工作,但我更喜欢使用装饰器的方式。

    【讨论】:

    • justOne 默认设置为false,所以你不需要声明它。
    猜你喜欢
    • 2021-01-09
    • 2020-05-18
    • 2017-04-04
    • 2020-11-08
    • 1970-01-01
    • 2018-12-23
    • 2019-09-16
    • 2013-03-31
    • 2020-11-09
    相关资源
    最近更新 更多