NestJs + mongoose ClassSerializerInterceptor不工作

xytpbqjk  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(165)

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

@Schema()
export class User {
  @Prop({type: String, required: true, unique: true, index:true})
  email: string;

  @Prop({type: String, required: true})
  username: string;

  @Prop({type: String, required: true, unique: true, index:true})
  handle: string;

  @Prop({type: String, required: true})
  @Exclude({ toPlainOnly: true })
  password: string;

  @Prop({type: String, default: () => randomBytes(16).toString('hex')})
  @Exclude({ toPlainOnly: true })
  emailVerifCode: string;

  //other properties
}

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

@Post('login')
  @UseGuards(AuthGuardLocal)
  @UseInterceptors(ClassSerializerInterceptor)
  async login(@CurrentUser() user: User) {

    return {
      user: user,
      token: await this.authService.getTokenForUser(user)
    }
  }


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

app.useGlobalInterceptors(
    new ClassSerializerInterceptor(app.get(Reflector))
  );


我使用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类的属性,这就是问题所在。你唯一的选择就是把它变成一个,这样你就可以返回一个示例类。

相关问题