カスタムスキーマタイプ

基本的なカスタムスキーマタイプの作成

Mongoose 4.4.0の新機能: Mongooseではカスタムタイプがサポートされます。ただし、カスタムタイプを使用する前に、ほとんどの使用事例ではオーバーキルであることに注意してください。カスタムゲッター/セッター仮想単一埋め込みドキュメントを使用すると、ほとんどの基本的なタスクを実行できます。

基本的なスキーマタイプの例を見てみましょう: 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');