I’ve spoken before about the two Andrew Meads Udemy classes I took a couple of years ago. That was where I was introduced to the concept of establishing a toJSON method or static on a database object.
In the class, we used the toJSON method to remove the password from the object. That way we could be sure that what was returned to the user after an API call wouldn’t have the password on it.
That meshes well with one of my pet theories, which is fixing stuff in the right spot. By putting the logic on the database model, then you don’t have to remember to strip it out each time you return a user via an API call.
I’ve used this now with Mongoose/MongoDB and Sequelize/Postgres
Recently, however I ran into some unexpected behavior. I needed to do some complex logic around a group of records returned from the database.
My approach was to create a new object with some additional information on it for each record that had been returned and then add the database object to this new object. The logic all worked splendidly, but when I converted the new object via JSON.stringify for logging purposes, a bunch of information was logged out that I expected to be removed via my toJSON method.
Apparently, when you add a database model/object to another object, stringifying that new object doesn’t take advantage of the logic defined on the model.
I went back to the logic and instead of creating a new object, I just attached additional information to each record I got back from the database. That did the trick quite handily, and I still get the advantage of the toJson method declared on my database model, so that is the pattern I’ll use going forward.