@@ -2970,7 +2970,6 @@ Document.prototype.$toObject = function(options, json) {
2970
2970
*
2971
2971
* If you want to skip transformations, use `transform: false`:
2972
2972
*
2973
- * if (!schema.options.toObject) schema.options.toObject = {};
2974
2973
* schema.options.toObject.hide = '_id';
2975
2974
* schema.options.toObject.transform = function (doc, ret, options) {
2976
2975
* if (options.hide) {
@@ -2986,7 +2985,26 @@ Document.prototype.$toObject = function(options, json) {
2986
2985
* doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
2987
2986
* doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }
2988
2987
*
2989
- * Transforms are applied _only to the document and are not applied to sub-documents_.
2988
+ * If you pass a transform in `toObject()` options, Mongoose will apply the transform
2989
+ * to [subdocuments](/docs/subdocs.html) in addition to the top-level document.
2990
+ * Similarly, `transform: false` skips transforms for all subdocuments.
2991
+ * Note that this is behavior is different for transforms defined in the schema:
2992
+ * if you define a transform in `schema.options.toObject.transform`, that transform
2993
+ * will **not** apply to subdocuments.
2994
+ *
2995
+ * const memberSchema = new Schema({ name: String, email: String });
2996
+ * const groupSchema = new Schema({ members: [memberSchema], name: String, email });
2997
+ * const Group = mongoose.model('Group', groupSchema);
2998
+ *
2999
+ * const doc = new Group({
3000
+ * name: 'Engineering',
3001
+ * email: 'dev@mongoosejs .io',
3002
+ * members: [{ name: 'Val', email: 'val@mongoosejs .io' }]
3003
+ * });
3004
+ *
3005
+ * // Removes `email` from both top-level document **and** array elements
3006
+ * // { name: 'Engineering', members: [{ name: 'Val' }] }
3007
+ * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });
2990
3008
*
2991
3009
* Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions.
2992
3010
*
0 commit comments