I have an Express app containing a Mongoose model, some of which's properties should not be serialized to JSON when returned to the end user as a HTTP response.
I can achieve this by attaching a transformer function to the schema that is called during serialization (this is a Mongoose feature):
MySchema.set('toJSON', { transform: function(doc,ret) {
delete ret.thisIsNotForUser;
} });
However, I also need to be able to add a property to ret
that is specific to the requesting user (whether the requesting user has previously favourited this entity) so effectively need the user in context within this toJSON
transformer method.
The only way to pass the user into this method, is to call e.g
res.jsonp(myModel.toJSON({ transform: true, user: req.user }));
which isn't ideal but is an acceptable compromise. Unfortunately this approach breaks down for e.g an array because toJSON is not implemented. (I can't call JSON.stringify() and still pass in my options! :()
I have considered a bunch of different solutions including:
Just adding the property in the route middleware / controller. (From what I can tell the new property won't be serialized to JSON unless it is added to the mongoose schema, so you have to add the properties up front which doesn't quite fit - these values should never be persisted as they are inferred / calculated)
Mongo aggregation - not ideal as completely changes the way in which entities are retrieved from the DB.
Any suggestions or insight towards an elegant solution will be much appreciated! I'm inclined to think this must be a reasonably common problem.