猫鼬高级自定义架构对象类型 [英] Mongoose advanced custom schema object type

查看:119
本文介绍了猫鼬高级自定义架构对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到高级的任何示例自定义架构类型在猫鼬> = 4.4中涉及自定义对象(或值对象).

I couldn't find any example of an advanced custom schema type involving custom objects (or value-objects) in 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; };

接下来,我实现一个自定义SchemaType,例如:

Next, I implement a 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);
}

我如何保证:

  1. 每次从db中将一个新对象水合"(猫鼬 init )时,我都会有一个多边形 实例,而不是普通对象.我了解它将使用cast 功能. assert(model.polygon instanceof Polygon)

  1. Every time a new object is "hydrated" from db (mongoose init), I will have a Polygon instance and not a plain object. I understand it will use the cast function. assert(model.polygon instanceof Polygon)

每次保存模型时,多边形"属性应为 编码并存储为普通对象表示形式 (Polygon.prototype.toObject())在这种情况下是mongodb中的 Array 对象.

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.

推荐答案

感谢@ vkarpov15在

I found a solution thanks to @vkarpov15 on github.com:

    需要
  1. SchemaType.prototype.cast() raw mongodb表示中正确地水化文档模型,并在数据无效的情况下引发错误.

  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.

要自定义mongodb持久性,我必须实现 toBSON() 在我的自定义类型对象原型(即Polygon)中的功能.

To customize mongodb persistence, I had to implement a toBSON() function in my custom type object prototype (i.e. Polygon).

model.toObject()/model.toJSON()当前不会在所有子级上递归调用toObject()/toJSON(),但是看起来像是

model.toObject() / model.toJSON() currently doesn't call recursively toObject()/toJSON() on all children, but it looks like it will be fixed. But I could overload it as temporary workaround assigning a custom schema.methods.toObject() instance method.

这篇关于猫鼬高级自定义架构对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆