Reputation: 2276
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!
Upvotes: 1
Views: 1289
Reputation: 1013
You can set your own implementation of toJSON
at schema level like the following:
var mySchema = new Schema({});
mySchema.set('toJSON', {
transform: function(doc, ret, options) {
ret.__length = 'set what do need';
return ret;
}
});
mongoose.model('mySchema', mySchema );
Upvotes: 1