#How to properly use DTO objects and Mongoose models together?

2 messages · Page 1 of 1 (latest)

granite radish
#

I'm currently working on a project where I need to handle data transformation from raw HTTP objects to UserDTO objects, then to simple objects, and finally to Mongoose objects using their respective interfaces. However, I'm finding it challenging to handle these objects correctly and ensure they are tightly coupled.

The documentation I've come across shows the two sides (DTO objects and Mongoose models) separately, but not how to integrate them properly. I have a few specific questions:

  • Should I use the instanceToPlain function to handle the transformation between objects?
  • What is the best approach for converting objects into different interfaces?
  • Is it necessary to transform the objects back to simple objects with a predefined interface before creating a Mongoose document?

I would appreciate any guidance or best practices on how to handle the integration of DTO objects and Mongoose models effectively, as well as any recommendations on how to properly convert objects between different interfaces.

Formatter by ChatGPT.

https://stackoverflow.com/questions/76382204/how-to-properly-use-dto-objects-and-mongoose-models-together-in-nestjs

Regards, Victor.

abstract escarp
#

a dto and mongoose have no relation to each other
the only purpose for a dto is to define a typing and as a validation schema
even if you would use things like the @Transform decorator this does not effect the body that is being send

a dto is completely separate from the body and a mongoose model is separate from those
i can see why you would prefer using a single class, but..

a dto will simply make a copy of the body and then compares this if it is valid or not
in fact typescript TypeScript will stop you from using a typing like a dto as a value
i'm afraid you will have to do this manually as there is no official or supported method to do this

of course where's a will is a way and there prob is some way around this, but i would suggest against trying this and just take this unfortunate L and do this manually

perhaps the core team or staff know something i dont, but still what you are asking is still unpractical and goes against standard coding ethics

sorry to shoot you down here like this sadcat