NestJs + mongoose ClassSerializerInterceptor不工作

xytpbqjk  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(235)

我在nestJs中有一个mongosee项目,我想从返回的对象中排除某些属性。具体来说:

  1. @Schema()
  2. export class User {
  3. @Prop({type: String, required: true, unique: true, index:true})
  4. email: string;
  5. @Prop({type: String, required: true})
  6. username: string;
  7. @Prop({type: String, required: true, unique: true, index:true})
  8. handle: string;
  9. @Prop({type: String, required: true})
  10. @Exclude({ toPlainOnly: true })
  11. password: string;
  12. @Prop({type: String, default: () => randomBytes(16).toString('hex')})
  13. @Exclude({ toPlainOnly: true })
  14. emailVerifCode: string;
  15. //other properties
  16. }

字符串
当我试着这样做的时候:

  1. @Post('login')
  2. @UseGuards(AuthGuardLocal)
  3. @UseInterceptors(ClassSerializerInterceptor)
  4. async login(@CurrentUser() user: User) {
  5. return {
  6. user: user,
  7. token: await this.authService.getTokenForUser(user)
  8. }
  9. }


我得到了一个空对象。我还尝试添加:

  1. app.useGlobalInterceptors(
  2. new ClassSerializerInterceptor(app.get(Reflector))
  3. );


我使用ClassSerializerInterceptor尝试的所有控制器都返回空对象。
但是我又得到一个空的对象作为响应。我尝试了其他的解决方案,但是没有一个成功。在这一点上有点绝望。
使用:“mongoose”:“^7.5.2”,“@nestjs/core”:“^10.0.0”

dpiehjr4

dpiehjr41#

这样做是行不通的。如果你去这里,https://docs.nestjs.com/techniques/serialization
你应该看到一个红色的通知:Note that we must return an instance of the class. If you return a plain JavaScript object, for example, { user: new UserEntity() }, the object won't be properly serialized.
这实际上意味着你的控制器必须返回一个类示例,意思是:return new User(...)
在你的例子中,响应中还有一个token,它不是你的User类的属性,这就是问题所在。你唯一的选择就是把它变成一个,这样你就可以返回一个示例类。

相关问题