【发布时间】:2016-10-31 21:06:15
【问题描述】:
我在 Mongoose >=4.4 中找不到任何涉及自定义对象(或 value-objects)的高级 custom schema type 示例。
假设我想使用自定义类型,例如:
function Polygon(c) {
this.bounds = [ /* some data */ ];
this.npoints = /* ... */
/* ... initialize polygon ... */
};
Polygon.prototype.area = function surfaceArea() { /**/ };
Polygon.prototype.toObject = function toObject() { return this.bounds; };
接下来,我实现了一个自定义 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);
}
我如何保证:
每次从 db (mongoose init) 中“水合”一个新对象时,我都会有一个 Polygon 实例而不是普通对象。我知道它将使用
cast功能。assert(model.polygon instanceof Polygon)每次我保存模型时,多边形属性都应该是 编码并存储为普通对象表示 (
Polygon.prototype.toObject()) 在这种情况下是 mongodb 中的Array对象。- 如果我使用
model.toObject(),它将递归调用model.polygon.toObject()以获得文档的完整纯对象表示。
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema mongoose-plugins