Mongoose advanced custom schema object type
I found a solution thanks to @vkarpov15 on github.com:
SchemaType.prototype.cast()
is needed to correctly hydrate the document model from raw mongodb representation, and throw an error in case of invalid data.To customize mongodb persistence, I had to implement a
toBSON()
function in my custom type object prototype (i.e.Polygon
).model.toObject()
/model.toJSON()
currently doesn't call recursivelytoObject()
/toJSON()
on all children, but it looks like it will be fixed. But I could overload it as temporary workaround assigning a customschema.methods.toObject()
instance method.