Mongoose SchemaType Options
In Mongoose, a schema type is a property of a schema that defines the type, required, and other characteristics of a field in a MongoDB collection. Schema types are used to validate the data that is stored in the collection and to define how the data should be stored in the database. You can define a schema type in a Mongoose schema by specifying the type of the field and any desired options.
Mongoose schema types have several options that you can use to customize the behavior of your schema. Some of the options available for schema types include:
- required: This option specifies whether a value for the field is required. If set to true, the field will be required in all documents. Not specifying this field will by default have a value of false.
- default: This option specifies a default value for the field. If a value for the field is not specified in a new document, the default value will be used.
- unique: This option specifies whether the values in the field must be unique across all documents in the collection (For ex. username field).
- index: This option specifies whether to create an index for the field. Indexes can improve the performance of queries and other operations that involve the field.
- sparse: This option specifies whether to create a sparse index for the field. A sparse index only includes documents that have a value for the indexed field.
- validate: This option allows you to specify a validation function for the field. The function will be called when a new document is saved, and the document will not be saved if the validation function returns an error.
- alias: This option allows you to specify an alias for the field. The alias can be used instead of the actual field name in queries and other operations.
- get and set: These options allow you to specify getter and setter functions for the field. The getter function will be called when the field is accessed, and the setter function will be called when the field is set.
Example 1: In the below example we are creating a Schema which only has a name field that is of type String, is required, has a by the default value of ‘John Doe’, should be unique, and index for this field will be created as the index is set to true, will include a sparse index, the length of the string should be greater than 3, has an alias name called ‘full_name’. Also, this schema value has to get and set functions and when the field is accessed it will change to uppercase, and when the field is set to value will change to lowercase.
Example 2: Below example is a schema of a book which have the title of a field that is of type String and is required, author which is of type String and is required, publishedDate which is of type Date and is required, pageCount which is of type Number and is required, a publisher which is of type String, coverImageUrl also of type String.
Please Login to comment...