node.js - Mongoose advanced custom schema object type -
i couldn't find example of advanced custom schema type involving custom objects (or value-objects) in mongoose >=4.4.
imagine want use custom type like:
function polygon(c) { this.bounds = [ /* data */ ]; this.npoints = /* ... */ /* ... initialize polygon ... */ }; polygon.prototype.area = function surfacearea() { /**/ }; polygon.prototype.toobject = function toobject() { return this.bounds; }; next, implement 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 assure that:
every time new object "hydrated" db (mongoose init), have polygon instance , not plain object. understand use
castfunction.assert(model.polygon instanceof polygon)every time save model polygon attribute should encoded , stored plain object representation (
polygon.prototype.toobject()) in casearrayobject in mongodb.- if use
model.toobject()recursively callmodel.polygon.toobject()have full plain object representation of document.
i found solution @vkarpov15 on github.com:
schematype.prototype.cast()needed correctly hydrate document model raw mongodb representation, , throw error in case of invalid data.to customize mongodb persistence, had implement
tobson()function in custom type object prototype (i.e.polygon).model.toobject()/model.tojson()doesn't call recursivelytoobject()/tojson()on children, looks fixed. overload temporary workaround assigning customschema.methods.toobject()instance method.
Comments
Post a Comment