简体   繁体   English

Mongoose高级自定义架构对象类型

[英]Mongoose advanced custom schema object type

I couldn't find any example of an advanced custom schema type involving custom objects (or value-objects ) in Mongoose >=4.4. 我在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: 接下来,我实现了一个自定义SchemaType,如:

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: 我怎样才能保证:

  1. Every time a new object is "hydrated" from db (mongoose init ), I will have a Polygon instance and not a plain object. 每当一个新对象从db(mongoose init )“水合”时,我将拥有一个Polygon实例,而不是一个普通对象。 I understand it will use the cast function. 我知道它会使用cast功能。 assert(model.polygon instanceof Polygon)

  2. 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 an Array object in mongodb. 每次我保存我的模型时,Polygon属性应该被编码并存储为普通对象表示( Polygon.prototype.toObject() ),在这种情况下是mongodb中的Array对象。

  3. If I use model.toObject() it will recursively call the model.polygon.toObject() to have a full plain object representation of the document. 如果我使用model.toObject() ,它将递归调用model.polygon.toObject()以获得文档的完整普通对象表示。

I found a solution thanks to @vkarpov15 on github.com : 我发现了一个解决方案感谢@ vkarpov15上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. 需要SchemaType.prototype.cast()才能从原始 mongodb表示中正确地水合文档模型,并在数据无效时抛出错误。

  2. To customize mongodb persistence, I had to implement a toBSON() function in my custom type object prototype (ie Polygon ). 要自定义mongodb持久性,我必须在自定义类型对象原型(即Polygon )中实现toBSON()函数。

  3. model.toObject() / model.toJSON() currently doesn't call recursively toObject() / toJSON() on all children, but it looks like it will be fixed . model.toObject() / model.toJSON()当前不会在所有子toObject()递归调用toObject() / toJSON() ,但看起来它将被修复 But I could overload it as temporary workaround assigning a custom schema.methods.toObject() instance method. 但我可以重载它作为临时解决方法分配自定义schema.methods.toObject()实例方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM