Mongoose advanced custom schema object type Mongoose advanced custom schema object type mongoose mongoose

Mongoose advanced custom schema object type


I found a solution thanks to @vkarpov15 on github.com:

  1. SchemaType.prototype.cast() is needed to correctly hydrate the document model from raw mongodb representation, and throw an error in case of invalid data.

  2. To customize mongodb persistence, I had to implement a toBSON() function in my custom type object prototype (i.e. Polygon).

  3. model.toObject() / model.toJSON() currently doesn't call recursively toObject()/toJSON() on all children, but it looks like it will be fixed. But I could overload it as temporary workaround assigning a custom schema.methods.toObject() instance method.