Skip to main content

SchemaType Options in Mongoose

SchemaType Options in Mongoose | Rustcode

SchemaType Options in Mongoose

Mongoose's SchemaType options provide extensive configuration capabilities to customize how each field in your schema behaves. These options include validation rules, default values, getters and setters for data transformation, indexing, and more.


Common SchemaType Options

  • type: The data type constructor (String, Number, etc.).
  • required: Specifies if the field must be present.
  • default: Specifies a default value or function.
  • enum: Limits the values to a fixed set.
  • alias: Alternate field name used in queries and documents.

Validation Options

  • min and max: Numeric limits.
  • minlength and maxlength: String length constraints.
  • match: Regular expression for string patterns.
  • validate: Custom validation function or config object.

Getters and Setters

  • get: Function to transform the value when retrieved.
  • set: Function to transform the value before saving.

Indexing Options

  • index: Enables MongoDB index on the field.
  • unique: Enforces unique constraint.
  • sparse: Index only documents with the field.
  • text: Creates text index on string fields.

Custom SchemaType Options

Plugins or custom SchemaTypes may define their own options to extend Mongoose's functionality. For example, the mongoose-autopopulate plugin uses an autopopulate option.


Example with Multiple Options

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    index: true,
    lowercase: true,
    trim: true,
    minlength: 3,
    maxlength: 30,
    validate: {
      validator: v => /^[a-z0-9]+$/.test(v),
      message: props => `${props.value} is not a valid username!`
    }
  },
  email: {
    type: String,
    required: true,
    unique: true,
    match: /.+\@.+\..+/
  },
  age: {
    type: Number,
    min: 0,
    max: 120,
    default: 18
  }
});

Best Practices

  • Use built-in validators before custom ones for efficiency.
  • Keep getters and setters simple for performance.
  • Design indexes according to your query patterns.
  • Document any custom options clearly for maintenance.

Conclusion

SchemaType options provide granular control to customize field behavior in Mongoose. Leveraging these options ensures data quality, consistency, and performance optimization in your MongoDB-backed Node.js applications.

Comments