短绒毛将类型“ Ref ”识别为“ T”,而不是“ ObjectId”

问题描述 投票:0回答:1

当我有如下课程时:

export class Application{
    @prop({ required: [true, 'app name is required'], unique: true })
    name!: string;

    @prop({ required: [true, 'component is required'], ref: Component})
    component!: Ref<Component>;
}

并且假设'Component'类具有'name'属性,我不能这样做:

let app: Application
const appName = 'appTest';
app = await (await this.findOne({ name: appName })).populate('component').execPopulate();
console.log(app.component.name);

因为它给了我以下错误:

Property 'name' does not exist on type 'Ref<Component, ObjectId>'.
Property 'name' does not exist on type 'ObjectId'

有没有一种方法可以让短毛绒感知类型为T(从Ref<T>开始)而不是ObjectId?

node.js typescript nestjs mongoose-populate typegoose
1个回答
0
投票

目前,对我来说非常有效的方法是使用类型保护,特别是Typegoose的isDocument and isDocumentArray。就像这样:

let app: Application
const appName = 'appTest';
app = await (await this.findOne({ name: appName })).populate('component').execPopulate();
if (isDocument(app.component)) {
console.log(app.component.name);
}
© www.soinside.com 2019 - 2024. All rights reserved.