SchemaType.prototype.transform()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Defines a custom function for transforming this path when converting a document to JSON.

Mongoose calls this function with one parameter: the current value of the path. Mongoose then uses the return value in the JSON output.

Example:

  1. const schema = new Schema({
  2. date: { type: Date, transform: v => v.getFullYear() }
  3. });
  4. const Model = mongoose.model('Test', schema);
  5. await Model.create({ date: new Date('2016-06-01') });
  6. const doc = await Model.findOne();
  7. doc.date instanceof Date; // true
  8. doc.toJSON().date; // 2016 as a number
  9. JSON.stringify(doc); // '{"_id":...,"date":2016}'