【发布时间】:2023-03-15 17:00:04
【问题描述】:
我正在尝试使用 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 的对象数组。
谢谢
【问题讨论】:
-
你应该升级到 typegoose 7.4,低于 7.0 的任何东西都支持
type: () =>(或参考)
标签: node.js typescript mongoose mongoose-schema typegoose