Stack - 带有 Typegoose 的 Type-graphql
问题 :
- BookRecommendation 类解析一本书(虚拟字段)
- Typegoose 返回正确的 book 填充值,该值通过 bookId foreign ref 解析
- 序列化的 type-graphql 响应不包括 book 对象,并且已经尝试了所有方法来解决这个问题。
序列化 book 对象的正确方法是什么?
@ObjectType()
export class BookRecommendation {
@Field()
readonly _id!: ObjectId;
@prop() @Field(() => Date)
createdAt!: Date;
@prop() @Field(() => Date)
updatedAt!: Date;
@prop() @Field()
sourceUrl!: string;
@prop() @Field()
recommendation!: string;
@prop({ref: Book, }) @Field(type => ObjectIdScalar)
bookId!: Ref<Book>;
@prop({ref: Influencer}) @Field(type => ObjectIdScalar)
influencerId!: Ref<Influencer>;
@prop({
ref: 'Book',
foreignField: '_id', // compare this value to the local document populate is called on
localField: 'bookId', // compare this to the foreign document's value defined in "foreignField",
justOne: true,
})
public book: Book;
}
export const MongooseBookReco = getModelForClass(BookRecommendation, {schemaOptions : {timestamps: true, toObject : { depopulate: false, versionKey: true, virtuals: true, getters: true } }});
// Service Class
@Service() // Dependencies injection
export default class BookRecommendationService {
constructor(private readonly bookRecoModel: BookRecommendationModel) {}
public async getById(_id: ObjectId): Promise<BookRecommendation | null> {
return MongooseBookReco.findById(_id).populate('book').exec();
}
public async find(): Promise<BookRecommendation[]> {
return MongooseBookReco.find().populate('book').exec();
}
public async addBookRecommendation(data: NewBookRecommendationInput): Promise<BookRecommendation> {
const newBookRecommendation = await this.bookRecoModel.create(data);
return newBookRecommendation;
}
}
// Resolver class trying to resolve the
@Query((returns) => BookRecommendation, {name: "BookRecommendation"})
async BookRecommendation(@Arg("id") id: ObjectId) {
const reco = await this.recoService.getById(id);
console.log(reco);
return reco;
}
// Console.log output of reco object above. It contains book
{
_id: 601e3a416f05d67955cf5477,
sourceUrl: 'https://twitter.com/joerogan/status/276827723358404608?s=20',
recommendation: 'Mind blowing book',
bookId: 601e2ebbdda47174163d718d,
influencerId: 601a362796e4c3a3650bcaf6,
__v: 0,
book: {
_id: 601e2ebbdda47174163d718d,
title: 'Sex at dawn',
amazonUrl: 'https://www.amazon.com/dp/0061707813?tag=mostrecommendedbooks-20&geniuslink=true',
__v: 0
},
id: '601e3a416f05d67955cf5477'
}
// Client graphl query the trigger above code
query {
BookRecommendation(id: "601e3a416f05d67955cf5477") {
recommendation
_id
bookId
influencerId
}
}
// Graph QL serialized output at client misses book object
{
"data": {
"BookRecommendation": {
"recommendation": "Mind blowing book",
"_id": "601e3a416f05d67955cf5477",
"bookId": "601e2ebbdda47174163d718d",
"influencerId": "601a362796e4c3a3650bcaf6"
}
}
}