自訂 Schema 類型
建立基本自訂 Schema 類型
Mongoose 4.4.0 新增功能: Mongoose 支援自訂類型。然而,在您使用自訂類型之前,請了解自訂類型對於大多數使用案例來說是過度的。您可以使用自訂 getters/setters、虛擬屬性和單一嵌入式文件來完成大多數基本任務。
讓我們來看一個基本 schema 類型的範例:1 位元組的整數。若要建立新的 schema 類型,您需要從 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');