M
M
mr-scrpt2020-10-03 11:02:51
MongoDB
mr-scrpt, 2020-10-03 11:02:51

How to properly serialize in nestjs?

I am getting data from mongi via nestjs . Let's say I want to get all users Here is the control that processes the endpoint

@Get('/getAll')
  async getAll() {
    return this.userService.getAll();
  }

Here is a service that receives data from mongi using mongus

async getAll(): Promise<User[]> {
    try {
      return await this.userModel.find().exec();
    } catch (error) {
      throw new BadRequestException('Users not found');
    }
  }

Here is the single user object in the response:

{
    
    "lastname": "Gabbana",
    "_id": "5f782ace2cdfcd297c373ba6",
    "name": "Dolce",        
    "password": "$2b$10$DSomsGAk4FuXUH6Knnmdz.9L2DWlFTfH.VOIM8VKYlDroOwKeh7kW",
    "__v": 0
 }

Everything works as it should. But I want to do data serialization. The nestjs documentation recommends using the @UseInterceptors(ClassSerializerInterceptor) decorator on the controller. And in the model, you need to apply the @Exclude()
decorator over the field that needs to be excluded during serialization. That is, like this:

@Schema()
export class User extends Document {
  @Prop()
  name: string;

  @Prop({ default: '' })
  lastname: string;
  
  @Exclude()
  @Prop()
  password: string;
}

export const UserSchema = SchemaFactory.createForClass(User);


But the problem is that now I get a very large object for each user, in which there is a lot of information I don’t need and at the same time, the password field is not excluded from the response, that is, the serialization did not go through and the answer is not the same.

{
    "$__": {
      "strictMode": true,
      "selected": {},
      "getters": {},
      "_id": {
        "_bsontype": "ObjectID",
        "id": {
          "type": "Buffer",
          "data": [
            95,
            120,
            42,
            206,
            44,
            223,
            205,
            41,
            124,
            55,
            59,
            166
          ]
        }
      },
      "wasPopulated": false,
      "activePaths": {
        "paths": {
          "role": "init",
          "registerAt": "init",
          "status": "init",
          "lastname": "init",
          "_id": "init",
          "name": "init",
          "email": "init",
          "phone": "init",
          "password": "init",
          "__v": "init"
        },
        "states": {
          "ignore": {},
          "default": {},
          "init": {
            "_id": true,
            "role": true,
            "registerAt": true,
            "status": true,
            "lastname": true,
            "name": true,
            "email": true,
            "phone": true,
            "password": true,
            "__v": true
          },
          "modify": {},
          "require": {}
        },
        "stateNames": [
          "require",
          "modify",
          "init",
          "default",
          "ignore"
        ]
      },
      "pathsToScopes": {},
      "cachedRequired": {},
      "session": null,
      "$setCalled": [],
      "emitter": {
        "_events": {},
        "_eventsCount": 0,
        "_maxListeners": 0
      },
      "$options": {
        "skipId": true,
        "isNew": false,
        "willInit": true,
        "defaults": true
      }
    },
    "isNew": false,
    "$locals": {},
    "$op": null,
    "_doc": {     
      
      "lastname": "Gabbana",
      "_id": {
        "_bsontype": "ObjectID",
        "id": {
          "type": "Buffer",
          "data": [
            95,
            120,
            42,
            206,
            44,
            223,
            205,
            41,
            124,
            55,
            59,
            166
          ]
        }
      },
      "name": "Dolce",
      
      
      "password": "$2b$10$DSomsGAk4FuXUH6Knnmdz.9L2DWlFTfH.VOIM8VKYlDroOwKeh7kW",
      "__v": 0
    },
    "$init": true
  }

Here such object comes for each user. This does not happen in the documentation and I did not find this in Google, a normal answer comes everywhere. Please tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question