我正在尝试使用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结果中有一个产品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数组的属性"products“不在结果中(缺少该属性):
{
"_id": "5f69aa0a56ca5426b44a86c5",
"name": "Fourniture"
}我不知道该怎么做。我认为问题出在家庭类@prop(ref)中。我看到一些人们使用@arrayProp的例子,但现在已经被弃用了。
我在一个简单对象中找到了关于ref的文档,但在Typegoose版本为5.9.1的对象数组中找不到。
谢谢
发布于 2020-12-02 02:34:00
除了使用旧版本的typegoose和新的“语法”
这是typegoose (7.4)中应该是这样的
@modelOptions({ schemaOptions: { collection: 'families' } })
export class Family {
@prop()
public _id?: string;
@prop()
public name?: string;
@prop({ ref: () => Product, required: true, default: [] })
public products!: Ref<Product>[]; // if Product's "_id" is also "string", then it would need to be ": Ref<Product, string>[];"
}https://stackoverflow.com/questions/65021307
复制相似问题