The recipe first
Avoid using ObjectId Type for Ambiguous Typing System Across Tiers by favoring Strings instead. This will result in simpler backend types and DTOs that are reusable at the front end without requiring any special tools. The main disadvantage of this approach is a slight decrease in performance, as strings are larger than ObjectIds and can impact fast sorting operations.
My story
This scenario originated from a real application. It seems we followed the basic rules in different steps but ultimately failed. It would be great if we had changed the architecture at the start. Our application has a stack consisting of NestJS, Angular, and Mongoose, all written in TypeScript.
We successfully implemented reusing typings across tiers, but it appeared complicated. Each tier had its own typing system, which could have been optimized. A clue to the problem is that the type of the primary field _id is ObjectId, a complex type present only on the backend. This made it unnatural for it to be used on both the frontend and backend.
Some tools were implemented to reuse these types on ObjectId. New UI types were created, which seemed to improve the application's typing system. However, the application became convoluted, and we didn't want to research the case of using plain string IDs because we thought our approach was correct and it worked everywhere except for MeteorJS projects.
If we refused to use the ObjectId type, we could eliminate the need for these tools, new UI types, and even DTOs that work on both frontend and backend. To test this idea, we created a separate project where I implemented the concept. The only disadvantage is the potential impact on MongoDB performance, which I couldn't measure.
Additionally, we experimented with meaningful primary IDs where demanded custom solutions where string type is demanded.
Top comments (0)