I would like to specify a custom transform of the JSON received by Mongoose as part of a query into a Javascript object. Typically, JSON.parse() or something similar is used. I would like to use my own transform function because I would like to include a new field called __length which is the length of the JSON received over the network. I do not want to use JSON.stringify(document_from_mongo).length() because I am performing an unnecessary stringify operation.
I have investigated using a custom toObject() or toJSON() method on the schema, but have not had any success. Thanks!
Content-Lengthshould be set in the headers ( unless streaming output ) and anything reading that string length from inside the object would of course need to "parse" the object first, which limits the utility of such data..find()and.aggregate()return the data as an array of data or a single object in thefindBy**varieties. For an output stream you need to specifically call.stream()( on find, cursor options for aggregate ) or call the native driver methods with much the same thing. So it is not a stream, but a plain object unless you ask otherwise. Even if you asked for a stream, what you are asking for is the "string length" of the JSON emitted. You cannot get that without stringifying the object or stream. Same points about utility noted above.