我正在尝试使用 Typegoose 获取嵌套的子文档数组。
在使用 Typegoose 进行重构之前,我使用 mongoose 获得了这个工作代码:
界面 :
export interface IFamily extends Document {
name: string;
products: IProduct[];
}
架构:
const familySchema: Schema = new Schema({
name: { type: String },
products: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
});
当我执行 Family.findById('5f69aa0a56ca5426b44a86c5') 时,我的 JSON 结果中有一个 Product ObjectId 数组。
重构后,我使用 Typegoose :
班级 :
@modelOptions({ schemaOptions: { collection: 'families' } })
export class Family {
@prop({ type: Schema.Types.ObjectId })
public _id?: string;
@prop({ type: String, required: false })
public name?: string;
@prop({ ref: () => Product, required: true, default: [] })
public products!: Product[];
}
当我做 :
getModelForClass(Family).findById('5f69aa0a56ca5426b44a86c5')
带有 ObjectId 数组的属性“产品”不在结果中(属性不存在):
{
"_id": "5f69aa0a56ca5426b44a86c5",
"name": "Fourniture"
}
我不知道如何使它工作。我认为问题出在家庭类@prop(ref) 中。我看到了一些人们使用 @arrayProp 但现在已弃用的示例。
我找到了关于 ref 的文档,其中包含一个简单的对象,但没有找到 Typegoose 版本 5.9.1 的对象数组。
谢谢