diff --git a/docs/schematypes.pug b/docs/schematypes.pug index ade9a47a067..7f2daac0bc4 100644 --- a/docs/schematypes.pug +++ b/docs/schematypes.pug @@ -34,6 +34,14 @@ block content
  • The `schema.path()` Function
  • + * [What is a SchemaType?](#what-is-a-schematype) + * [The `type` Key](#type-key) + * [SchemaType Options](#schematype-options) + * [Usage Notes](#usage-notes) + * [Getters](#getters) + * [Custom Types](#customtypes) + * [The `schema.path()` Function](#path) +

    What is a SchemaType?

    You can think of a Mongoose schema as the configuration object for a @@ -125,6 +133,57 @@ block content m.save(callback); ``` +

    The `type` Key

    + + `type` is a special property in Mongoose schemas. When Mongoose finds + a nested property named `type` in your schema, Mongoose assumes that + it needs to define a SchemaType with the given type. + + ```javascript + // 3 string SchemaTypes: 'name', 'nested.firstName', 'nested.lastName' + const schema = new Schema({ + name: { type: String }, + nested: { + firstName: { type: String }, + lastName: { type: String } + } + }); + ``` + + As a consequence, [you need a little extra work to define a property named `type` in your schema](/docs/faq.html#type-key). + For example, suppose you're building a stock portfolio app, and you + want to store the asset's `type` (stock, bond, ETF, etc.). Naively, + you might define your schema as shown below: + + ```javascript + const holdingSchema = new Schema({ + // You might expect `asset` to be an object that has 2 properties, + // but unfortunately `type` is special in Mongoose so mongoose + // interprets this schema to mean that `asset` is a string + asset: { + type: String, + ticker: String + } + }); + ``` + + However, when Mongoose sees `type: String`, it assumes that you mean + `asset` should be a string, not an object with a property `type`. + The correct way to define an object with a property `type` is shown + below. + + ```javascript + const holdingSchema = new Schema({ + asset: { + // Workaround to make sure Mongoose knows `asset` is an object + // and `asset.type` is a string, rather than thinking `asset` + // is a string. + type: { type: String }, + ticker: String + } + }); + ``` +

    SchemaType Options

    You can declare a schema type using the type directly, or an object with @@ -234,7 +293,7 @@ block content * `min`: Date * `max`: Date -

    Usage notes

    +

    Usage Notes

    String