I have the following mongoose schema used in my MEAN app:
// schema
var categorySchema = new Schema ({
sId: String,
name: String,
parentId: String,
merchants: {},
attributes: {}, /* used to generate pivots and then discarded. */
pivots: [],
_id: {type: String, select: false},
/*other elements in db also not returned by using select: false*/
});
here's the problem. I have a mongodb that is not created by my app, rather its actual schema is defined elsewhere. I have access to this data but want it in a completely different format then what is actually in the database. This is working great by using:
categorySchema.options.toJSON = {
transform: function(doc, ret, options) {
however the schema doesn't represent the full API contract because the "attributes" field in the Schema is deleted in the transform. Pivots aren't in the database but are needed in the schema for mongoose to return it. Thankfully I like this, I want the schema to reflect exactly what I am returning, not what is in the database because frankly, it's a mess and I'm heavily transforming it, so I can give it to other engineers and use it for automated testing.
How do I get attributes out of the schema but still able to use in the transform?
turns out mongoose has function transforms. So I can do:
merchants: { type: {}, get: objToArr},
and that function is called.
just be sure to set:
Schema.set('toObject', { getters: true }); Schema.set('toJSON', { getters: true });
to true.