Search code examples
typescriptmongoosetypegraphql

Mongoose: Property 'forEach' does not exist on type 'ObjectId | [BaseAction]'


I just get this error. Property 'forEach' does not exist on type 'ObjectId | [BaseAction]'.

The error is on the last line, the code is :

    ServiceModel.findOne({name: "slack"}).populate({
        path: 'actions',
        model: 'BaseActionModel',
    }).then((res) => {
        if (!res?.actions) return // null verif

        res.actions.forEach((action: BaseAction) => {

I search but I found nothing on it. To add more context, my models are :

@ObjectType({description: 'Services'})
export class Service {
    @Field(() => ID)
    id!: string;

    @Field()
    @Property()
    name!: String;

    @Field()
    @Property()
    out_url!: String;

    @Field()
    @Property()
    in_url!: String;

    @Field((_type) => [BaseAction])
    @Property({ref: BaseAction})
    actions: Ref<[BaseAction]>;
}

You can ask for more code if you want


Solution

  • In order to perform a OneToMany relationship in type-graphql, you need to use typeorm.

    import {ObjectType, Field, ID, InputType} from 'type-graphql';
    import {prop as Property, getModelForClass, Ref} from '@typegoose/typegoose';
    import {OneToMany} from "typeorm"; // import this
    
    @ObjectType({description: 'Services'})
    export class Service {
        @Field(() => ID)
        id!: string;
    
        @Field()
        @Property()
        name!: String;
    
        @Field()
        @Property()
        out_url!: String;
    
        @Field()
        @Property()
        in_url!: String;
    
        @Field((_type) => [BaseAction])
        // @ts-ignore type unused
        @OneToMany(type => BaseAction, action => action.id) // add this
        actions?: BaseAction[];
    }