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

5

我目前正在一个虚拟人口的项目上工作,这是非常必要的:

有一个客户计划、一个文档计划以及其他一些引用客户的计划。在客户计划内我想填充这些引用的内容。

我已经使用 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' }[];

现在我正在尝试使用 nestjs/mongoose 实现这一点,仅在删除 typegoose 后使用:

@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它们是否可能?

1个回答

3

好的,我成功让事情重新工作起来了,但不是最优的方式:

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

export const CustomerSchema = SchemaFactory.createForClass(Customer);

我刚刚不得不“手动”添加虚拟填充:
CustomerSchema.virtual('documents', {
  ref: 'DMSDocument',
  localField: '_id',
  foreignField: 'links.customers',
  justOne: false
}); 

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


1
“justOne” 默认设置为“false”,因此您实际上不需要声明它。 - Javi Marzán

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接