Getters in SchemaTypes in Mongoose
Getters in Mongoose SchemaTypes are functions that allow you to transform or manipulate the raw value of a field before it is returned when accessing a document property. This feature is useful for formatting, masking, or computing derived values on data fetched from MongoDB.
Table of Content
What Are Getters?
- Getters are functions defined on schema fields that run every time you access a property on a Mongoose document.
- They let you transform the value before returning it to your application code.
- Common uses include formatting dates, obscuring sensitive data, and computing derived properties on the fly.
Defining Getters in Schemas
You define a getter using the get
option inside a schema path definition.
const userSchema = new mongoose.Schema({
name: String,
birthdate: {
type: Date,
get: val => val.toISOString().substring(0, 10) // Format date as YYYY-MM-DD
}
});
Usage Examples
Example: Formatting date and obfuscating an email before returning.
const userSchema = new mongoose.Schema({
email: {
type: String,
get: val => val.replace(/(.{2})(.*)(?=@)/, (p1, p2) => p2 + '***')
},
createdAt: {
type: Date,
default: Date.now,
get: val => val.toLocaleString()
}
});
const User = mongoose.model('User', userSchema);
const user = new User({ email: 'example@example.com' });
console.log(user.email); // ex***@example.com
console.log(user.createdAt); // formatted local datetime string
Best Practices
- Use getters primarily for read transformations, not for data mutation.
- Keep getter logic performant and simple to avoid slowing document access.
- Enable virtuals and getters in output by setting
toJSON: { getters: true }
in the schema options if needed. - Avoid defining getters on arrays or complex nested objects to prevent unexpected behavior.
- Test your getters carefully to ensure they don't interfere with data integrity or change tracking.
Quick Reference Table
Feature | Description | Code Example |
---|---|---|
Getter Function | Transforms field value when accessed | { get: val => val.toUpperCase() } |
Defined On | Schema field definition | path: { type: String, get: fn } |
Use Case | Formatting, masking, computed properties | Formatting dates, hiding emails |
Enable In JSON Output | Set toJSON: { getters: true } in options |
new Schema({...}, { toJSON: { getters: true } }) |
Conclusion
Getters in Mongoose SchemaTypes provide a clean and powerful way to manipulate field data on-the-fly when accessing documents. They enhance your ability to present data in the right format or protect sensitive fields without modifying the underlying stored data, helping you build robust Node.js applications with MongoDB.
Comments
Post a Comment