SchemaType Options in Mongoose
SchemaType options in Mongoose allow you to configure individual schema paths extensively. These options control validation, default values, transformation behaviors, indexing, and more, making sure your MongoDB data aligns with your application's requirements.
Table of Content
Common SchemaType Options
type: Specifies the JavaScript constructor for the path (e.g. String, Number).required: Whether the field is mandatory (trueor a custom error message).default: Default value if none is provided.enum: Limits the values to a defined set.alias: Defines an alternate name used in documents.
Validation Options
minandmax: Numeric limits.minlengthandmaxlength: String length constraints.match: Regex pattern validation.validate: Custom validation function or object.
Getters and Setters
Configure transformation functions to run when reading or writing the field's value.
get: Function to modify the value when accessed.set: Function to transform incoming value before saving.
Indexing Options
index: Creates a MongoDB index on the field.unique: Ensures uniqueness of the field.sparse: Creates an index only for documents with the field defined.text: Creates a text index for search purposes.
Custom SchemaType Options
Mongoose plugins and custom SchemaTypes can extend options with specialized behaviors. For example, mongoose-autopopulate uses autopopulate option for automatic population.
Example Using Multiple Options
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 validation options wherever possible before writing custom validators.
- Keep getter and setter functions lightweight to maintain performance.
- Ensure indexes are aligned with your queries for optimal performance.
- Document any custom options added by plugins or code to maintain team clarity.
Conclusion
SchemaType options in Mongoose are powerful tools that allow fine control over each path's type, validation, transformation, and indexing. Mastering these options will lead to better data consistency, improved query performance, and cleaner application code in your MongoDB projects.
Comments
Post a Comment