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:

  1. every time new object "hydrated" db (mongoose init), have polygon instance , not plain object. understand use cast function. assert(model.polygon instanceof polygon)

  2. every time save model polygon attribute should encoded , stored plain object representation (polygon.prototype.toobject()) in case array object in mongodb.

  3. if use model.toobject() recursively call model.polygon.toobject() have full plain object representation of document.

i found solution @vkarpov15 on github.com:

  1. schematype.prototype.cast() needed correctly hydrate document model raw mongodb representation, , throw error in case of invalid data.

  2. to customize mongodb persistence, had implement tobson() function in custom type object prototype (i.e. polygon).

  3. model.toobject() / model.tojson() doesn't call recursively toobject()/tojson() on children, looks fixed. overload temporary workaround assigning custom schema.methods.toobject() instance method.


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -