I couldn't find any example of an advanced custom schema type involving custom objects (or value-objects) in Mongoose >=4.4.
Imagine that I want to use a custom type like:
function Polygon(c) {
this.bounds = [ /* some data */ ];
this.npoints = /* ... */
/* ... initialize polygon ... */
};
Polygon.prototype.area = function surfaceArea() { /**/ };
Polygon.prototype.toObject = function toObject() { return this.bounds; };
Next, I implement a custom SchemaType like:
function PolygonType(key, options) {
mongoose.SchemaType.call(this, key, options, 'PolygonType');
}
PolygonType.prototype = Object.create(mongoose.SchemaType.prototype);
PolygonType.prototype.cast = function(val) {
if (!val) return null;
if (val instanceof Polygon) return val;
return new Polygon(val)
}
PolygonType.prototype.default = function(val) {
return new Polygon(val);
}
How can I assure that:
Every time a new object is "hydrated" from db (mongoose init), I will have a Polygon instance and not a plain object. I understand it will use the
cast
function.assert(model.polygon instanceof Polygon)
Every time I will save my Model the Polygon attribute should be encoded and stored as a plain object representation (
Polygon.prototype.toObject()
) that in this case is anArray
object in mongodb.- If I use
model.toObject()
it will recursively call themodel.polygon.toObject()
to have a full plain object representation of the document.