自定义模式类型
创建基本自定义模式类型
Mongoose 4.4.0 中的新功能:Mongoose 支持自定义类型。但是,在使用自定义类型之前,请了解自定义类型对于大多数用例来说过于复杂。您可以使用 自定义 getter/setter、虚拟属性 和 单个嵌入式文档 来完成大多数基本任务。
让我们来看一个基本模式类型的示例:一个 1 字节的整数。要创建新的模式类型,您需要从 mongoose.SchemaType
继承并向 mongoose.Schema.Types
添加相应的属性。您需要实现的唯一方法是 cast()
方法。
class Int8 extends mongoose.SchemaType {
constructor(key, options) {
super(key, options, 'Int8');
}
// `cast()` takes a parameter that can be anything. You need to
// validate the provided `val` and throw a `CastError` if you
// can't convert it.
cast(val) {
let _val = Number(val);
if (isNaN(_val)) {
throw new Error('Int8: ' + val + ' is not a number');
}
_val = Math.round(_val);
if (_val < -0x80 || _val > 0x7F) {
throw new Error('Int8: ' + val +
' is outside of the range of valid 8-bit ints');
}
return _val;
}
}
// Don't forget to add `Int8` to the type registry
mongoose.Schema.Types.Int8 = Int8;
const testSchema = new Schema({ test: Int8 });
const Test = mongoose.model('CustomTypeExample', testSchema);
const t = new Test();
t.test = 'abc';
assert.ok(t.validateSync());
assert.equal(t.validateSync().errors['test'].name, 'CastError');
assert.equal(t.validateSync().errors['test'].message,
'Cast to Int8 failed for value "abc" (type string) at path "test"');
assert.equal(t.validateSync().errors['test'].reason.message,
'Int8: abc is not a number');