无法让 mongoose 虚拟填充并在 NestJS 应用程序中运行

Jan*_*nik 5 mongoose mongoose-populate nestjs

我目前正在开发一个项目,其中虚拟填充是非常必要的:

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

我已经有一个使用 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' }[];
Run Code Online (Sandbox Code Playgroud)

现在我试图仅在删除 typegoose 后使用Nestjs/mongoose来实现此目的:

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

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

@Schema({ toJSON: { virtuals: true, getters: true }, toObject: { virtuals: true, getters: true }})
Run Code Online (Sandbox Code Playgroud)

该模型的填充如下:

this.customerModel.findOne(params)
.populate('documents', '', 'DMSDocument')
.populate('repairs', '', 'Repair')
Run Code Online (Sandbox Code Playgroud)

我不知何故陷入困境 - 我只是得到空数组,没有错误。我缺少什么?他们甚至可以使用 Nestjs/mongoose 吗?

Jan*_*nik 3

好吧,我设法让事情再次运行,但不是以首选方式:

定义类并将其转换为模式后

export const CustomerSchema = SchemaFactory.createForClass(Customer);
Run Code Online (Sandbox Code Playgroud)

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

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

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