Create a Custom EJSON Type

Meteor EJSON allows us to create custom types that are serialized and deserialized over the wire

Good job! That's it for "Create a Custom EJSON Type."

Need a second look? Watch again

Create a Custom EJSON Type

Meteor EJSON allows us to create custom types that are serialized and deserialized over the wire. Custom types can be sent as a parameter to a Meteor method, published in a subscription, or even stored in MongoDB. In this episode we'll write a constructor function that has a prototype method and make it a custom EJSON type.

  • Meteor
  • Tutorial
**Related lessons:** * <a href="http://www.eventedmind.com/posts/meteor-what-is-ejson">What is EJSON?</a> <p class="code-block-title">app.js</p> ```javascript function Address (city, state) { this.city = city; this.state = state; } Address.prototype = { constructor: Address, toString: function () { return this.city + ', ' + this.state; }, // Return a copy of this instance clone: function () { return new Address(this.city, this.state); }, // Compare this instance to another instance equals: function (other) { if (!(other instanceof Address)) return false; return this.city == other.city && this.state == other.state; }, // Return the name of this type which should be the same as the one // padded to EJSON.addType typeName: function () { return "Address"; }, // Serialize the instance into a JSON-compatible value. It could // be an object, string, or whatever would naturally serialize // to JSON toJSONValue: function () { return { city: this.city, state: this.state }; } }; // Tell EJSON about our new custom type EJSON.addType("Address", function fromJSONValue(value) { // the parameter - value - will look like whatever we // returned from toJSONValue from above. console.log(value); return new Address(value.city, value.state); }); ```
Join the Discussion

Want to leave a comment? .