![](/img/trans.png)
[英]Mongoose Schema type as a custom interface from TypeScript?
[英]Mongoose advanced custom schema object type
我在Mongoose> = 4.4中找不到任何涉及自定義對象(或值對象 )的高級 自定義模式類型的示例。
想象一下,我想使用自定義類型,如:
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屬性應該被編碼並存儲為普通對象表示( Polygon.prototype.toObject()
),在這種情況下是mongodb中的Array
對象。
model.toObject()
,它將遞歸調用model.polygon.toObject()
以獲得文檔的完整普通對象表示。 我發現了一個解決方案感謝@ vkarpov15上github.com :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.