TypeGraphQL如何避免未输入的SNS字段以null值存入MongoDB
解决方案
问题根因有两个:
SNSInput中给每个可选字段配置了defaultValue: null,用户未传值时会主动返回null而非undefined- 写入MongoDB时直接将所有SNS字段传入,未过滤空值
第一步:修改SNSInput配置
删除每个Field的defaultValue: null配置,修改后代码如下:
@InputType() export class SNSInput { @Field({ nullable: true }) facebook?: string; @Field({ nullable: true }) instagram?: string; @Field({ nullable: true }) youtube?: string; @Field({ nullable: true }) blog?: string; @Field({ nullable: true }) twitter?: string; }
这一步修改后,用户未输入的字段值会变为undefined而非null。
第二步:写入数据库前过滤空值字段
不要直接解构所有SNS字段后传入create方法,先过滤掉值为undefined的字段再写入,Resolver代码修改示例:
@Resolver() export class NameCardCreateResolver { @Mutation(() => BaseMutationResponse) async namecardCreate( @Arg("chosenSNSUrls", () => SNSInput) snsInput: SNSInput, // 保留完整输入对象用于过滤 @Arg("owner", () => NameCardOwner) { ownerEmail }: NameCardOwner ): Promise<BaseMutationResponse> { const response = new BaseMutationResponse(); try { // 过滤掉SNS对象中值为undefined、null的字段,也可根据需求新增空字符串过滤逻辑 const cleanedSNS = Object.fromEntries( Object.entries(snsInput).filter(([_, value]) => value != null) ) await NameCardModel.create({ sns: cleanedSNS, owner: { email: ownerEmail, }, // 剩余原有逻辑保持不变
可选优化:如果你使用Mongoose作为MongoDB的ODM,可以直接在Schema配置中开启
removeUndefined: true,Mongoose会自动移除值为undefined的字段,无需手动编写过滤逻辑。
内容的提问来源于stack exchange,提问作者yl K
相关产品推荐
相关产品推荐

