Typegoose and TypeGraphQL - @FieldResolver not working

67 Views Asked by At

I have try to get the user by the userid which stored in the notice, but I get undefined in the FieldResolver.

Notice Schema

@ObjectType({description: "Notice Schema"})
export class Notice extends Base{
    @NField() @prop() userId: string;
    @NField((type: any) => User) @prop({ref: () => User,require: true}) user: Ref<User>;
    @NField() @prop() title: string;
    @NField() @prop() type: string;
    @NField() @prop() lostDate: Date;
    @NField({nullable: true}) @prop({default: null}) foundDate: Date;
    @NField({nullable: true}) @prop({default: null}) found_user_id: string;
    @NField() @prop() description: string;
    @NField() @prop() venue: string;
    @NField() @prop() contact: string;
    @NField({nullable: true}) @prop() imageDir: string;
}

Notice Resolver

@Resolver((of) => Notice)
export class NoticeResolver{
    constructor() {}

    @FieldResolver()
    async user(@Root() notice: Notice){
        console.log(notice.userId)
        return await UserModel.findById(notice.userId)
    }

    @Mutation(() => Notice)
    async createNotice(
        @Arg("noticeInfo") noticeInfo: NoticeInput
    ) {
        let notice = new NoticeModel()
        for (let key in noticeInfo){
            notice[key] = noticeInfo[key]
        }
        return (await NoticeModel.create(notice)).save()
    }

    @Query(() => [Notice])
    async findNoticeByUserId(
        @Arg("user_id") user_id: string
    ) {   
        let result:any = await NoticeModel.find({userId: user_id})
        return result
    }


    @Query(() => [Notice])
    async findNoticeById(
        @Arg("notice_id") notice_id: string
    ) {   
        return NoticeModel.aggregate([
            {
                $match: { _id: notice_id },   
            },
        ])
    }


    @Query(() => [Notice])
    async allNotice() {
        return await NoticeModel.find({})
    }


    
}

And the query

query{
    allNotice{
      _id
      userId
      title
      type
      lostDate
      foundDate
      found_user_id
      description
      venue
      contact
      imageDir
      user{
        name
        phone
        email
        country
      }
    }
}

When a run the query the console.log in the Field Resolver shown "undefined"

I do not really know what happen, I am also follow the docmentation in the type-graphql and the version is ^1.1.1

0

There are 0 best solutions below