Creating a Basic Custom Schema Type - 图1mongoose

Creating a Basic Custom Schema Type - 图2mongoose

[

Creating a Basic Custom Schema Type ](#creating-a-basic-custom-schema-type)

New in Mongoose 4.4.0: Mongoose supports custom types. Before you reach for a custom type, however, know that a custom type is overkill for most use cases. You can do most basic tasks with custom getters/setters, virtuals, and single embedded docs.

Let's take a look at an example of a basic schema type: a 1-byte integer. To create a new schema type, you need to inherit from mongoose.SchemaType and add the corresponding property to mongoose.Schema.Types. The one method you need to implement is the cast() method.

  1. function Int8(key, options) {
  2. mongoose.SchemaType.call(this, key, options, 'Int8');
  3. }
  4. Int8.prototype = Object.create(mongoose.SchemaType.prototype);
  5. // `cast()` takes a parameter that can be anything. You need to
  6. // validate the provided `val` and throw a `CastError` if you
  7. // can't convert it.
  8. Int8.prototype.cast = function(val) {
  9. var _val = Number(val);
  10. if (isNaN(_val)) {
  11. throw new Error('Int8: ' + val + ' is not a number');
  12. }
  13. _val = Math.round(_val);
  14. if (_val < -0x80 || _val > 0x7F) {
  15. throw new Error('Int8: ' + val +
  16. ' is outside of the range of valid 8-bit ints');
  17. }
  18. return _val;
  19. };
  20. // Don't forget to add `Int8` to the type registry
  21. mongoose.Schema.Types.Int8 = Int8;
  22. var testSchema = new Schema({ test: Int8 });
  23. var Test = mongoose.model('CustomTypeExample', testSchema);
  24. var t = new Test();
  25. t.test = 'abc';
  26. assert.ok(t.validateSync());
  27. assert.equal(t.validateSync().errors['test'].name, 'CastError');
  28. assert.equal(t.validateSync().errors['test'].message,
  29. 'Cast to Int8 failed for value "abc" at path "test"');
  30. assert.equal(t.validateSync().errors['test'].reason.message,
  31. 'Int8: abc is not a number');